Search code examples
javascriptvue.jsstatestorevuex

vuex: set default values from async function


I have the following store:

export const store = new Vuex.Store({
    state: {
        someProp: someAsyncFn().then(res => res),
        ...
    },
    ...
})

Somehow it looks like someProp isn't waiting for the values to be resolved. Is this bad practise? Should I set an empty object as default and update the state via mutation on load?


Solution

  • You should be doing it like this :

    export const store = new Vuex.Store({
        state: {
            someProp: null
            ...
        },
        mutations:{
            initializeSomeProp: (state, payload) => {
                state.someProp = payload;
            }
        },
        actions:{
            asyncSomeProp: ({commit}) => {
                someAsyncFn().then(res => commit('initializeSomeProp', res))
            } 
        }
    }) 
    

    Asynchronous functionality should be handled by actions. You can use this action asyncSomeProp and the commit a mutation initializeSomeOrop by passing the res which you get in your async callback as a payload parameter.

    Then if you want to initialize your someProp in some component then you can dispatch your asyncSomeProp action in created lifecycle hook of that component as follows:

    created(){
        this.$store.dispatch('asyncSomeProp');
    }