Search code examples
vue.jsvuexflux

Is it right to dispatch a part of the vuex store as a payload of an action?


I've got some questions about this vuex store

export default {
    state: {
        resultSet: [
            {
                name: "result 1"
                deep: {
                    inside: {
                        isLoading: false
                    }
                }
            },
            {
                name: "result 2"
                deep: {
                    inside: {
                        isLoading: false
                    }
                }
            },
        ]
    },
    actions: {
        /*
        r is an item of the resultSet in the store (so r is a part of the store)
        */
        sendQuery(context, r) {
            //Here I mutate r directly (it means that I mutated the store directly without commit a mutation)

            r.deep.inside.isLoading = true;

            //Everything work, the UI is updated along with the state changes, but I'm not sure that 
            //I'm doing the right thing (mutate the store indirectly without committing a mutation)
        }
    }
}

Questions:

  1. Is it right to dispatch a part of the store as a payload of an action? => the action might directly change the state of r.

  2. Is it right to mutate r.deep.inside.isLoading=true in the above action?


Solution

    1. Is it right to dispatch a part of the store as a payload of an action? => the action might directly change the state of r.

    It's fine for state to be in the payload. But actions cannot directly modify state.

    1. Is it right to mutate r.deep.inside.isLoading=true in the above action?

    No. From the docs:

    Instead of mutating the state, actions commit mutations.

    Actions should only commit mutations (sort of like "event bus" and/or mutex in Vuex).

    It may seem silly for actions (which are similar to events themselves) to dispatch other event-like things, but mutation events ("commits") have special rules, like how they must be synchronous, whereas actions can perform async tasks before committing mutations.

    Take advantage of strict mode while you're developing, that way Vuex will certainly inform you when you are modifying state incorrectly.