use onMounted is a pinia store work well #1508
-
Reproductionjust as follow Steps to reproduce the bugI have a question that has been bothering me. import { onMounted, ref } from 'vue';
import { defineStore } from 'pinia';
import apiReq from 'api'
export default defineStore('test-store', () => {
const arr = ref([])
// init data after mount
onMounted(async () => {
const data = await apiReq()
arr.value = data
})
return {arr}
}) In definition, it's used as a vue composition which uses onmounted or maybe other vue-hook function. if this is not a bug, does pinia would like to recommend this definition? Expected behavioronmouted wont be work Actual behaviorwork as usual Additional informationNo response |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 1 reply
-
You should usually avoid it as the store could be instantiated outside of a component lifecycle and therefore never trigger the function passed to You should also guard it: import { getCurrentInstance } from 'vue'
// ...
if (getCurrentInstance()) {
onMounted(() => {
})
} An equivalent to |
Beta Was this translation helpful? Give feedback.
-
is there any plan to create a eslint rule sets for it? |
Beta Was this translation helpful? Give feedback.
-
Hello, @posva, isn't |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
I've just had to use this. |
Beta Was this translation helpful? Give feedback.
You should usually avoid it as the store could be instantiated outside of a component lifecycle and therefore never trigger the function passed to
onMounted()
.You should also guard it:
An equivalent to
onUnmounted()
for stores isonScopeDispose()
(https://vuejs.org/api/reactivity-advanced.html#onscopedispose) but this only triggers if you dispose of the store withstore.$dispose()