'How to make vuex actions wait until a specific action completed to define state
Here's my vuex state:
state: { id: null }
Actions:
actions: {
async getId({ state }) {
const id = await api.getId()
commit('setId', id)
}
async getById({ state }) {
return await api.get(id: state.id)
}
}
I have a mounted() in my main App.vue file:
// App.vue (parent)
async mounted() {
// set 'id' globally
await this.$store.dispatch('getId')
}
The problem begins here that I also have another mounted() in one of my child views/components:
// Component.vue (child)
async mounted() {
await this.$store.dispatch('getById', this.$store.state.id) // <-- notice this
}
In the last code, I use this.$store.state.id which is null when at the run time. It's because child components created before the parent (App.vue). How do you solve such problems? I chould check if the id is null before running getById in the mounted. But mounted is called only once when the component is created so if the id is null at that time, it'll never dispatch the getById...
Please note that this is just an example code. I tried to illustrate the problem with that code.
Solution 1:[1]
If the mounted function is relying on a value that is not set, you can prevent the component from mounting in the first place. You can do this by making the rendering of your child component conditional.
Example:
<template>
<my-child-component v-if="$store.state.id !== null"/>
<my-loading-spinner v-else />
</template>
Usually I implement something a little more complex which watches the state of the API calls (for error handling) and use computed values such as isLoaded instead of in-lining the validation in template (for readability)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel |
