I have a Vuex
store set up in my application with defined getters
, actions
, and mutations
. One of the actions, called initConfiguration
, is responsible for fetching data from an API and then committing this data to a mutation that updates the state. This action is crucial as it loads essential metadata and configurations required by other actions in the store. In my main component, I have included some initialization code within the mounted
lifecycle hook:
new Vue({
el: '#app',
store,
render: h => h(App),
mounted() {
store.dispatch('initConfiguration').then(() => {
store.dispatch('loadData')
})
}
})
The issue I am encountering is that the state is not being updated before the subsequent action loadData
is triggered, resulting in errors due to missing or uninitialized data. I want to avoid calling the loadData
action directly from the initConfiguration
action to adhere to best practices.
Here is my Vuex store implementation...
export default Vuex.Store({
state: {
metadata: {
initialized: false,
config: { }
}
},
mutations: {
setConfiguration(state, config) {
state.metadata.config = config
state.metadata.initialized = true
}
},
actions: {
initConfiguration({commit}) {
axios.get('configuration').then((response) => {
commit('setConfiguration', response.data)
})
},
loadData({commit, state}) {
axios.get(state.metadata.config.tenantDataUrl) // crashes here due to undefined data
.then((response) => { ... });
}
}
})
How can I properly chain actions together and ensure that the state is updated in a timely manner?