Jesus Jimenez
Jesus Jimenez

Reputation: 361

Accessing Vuex module mutated state from a parent module

I'm sending an axios.post with the whole state of my Vuex store which includes several states from other modules. Inside one of these modules, there's an array which is being mutated as normal as state.array would mutate through dispatching that module's actions/mutations. Afterwards, I'm sending the axios request, but it sends state as if it wouldn't have been changed.

Here's the code:

Parent module:

export default {
    namespaced: true,
    modules: {
        // ... Modules
        person: person, // Includes all the state from person module
    },
    state: {
        // State
    },
    getters: {
        // ... Getters
    },
    actions: {
        // ... Actions
        update({commit, dispatch, state, rootState}) {
            axios.post(url, state) // Should send local state plus person's state
        },
    },
    mutations: {
        // ... Mutations
    },
}

person module

export default {
    namespaced: true,
    modules: {
        // ... Modules
    },
    state: {
        // ... State
        array: [1,2,3,4,5],
    },
    getters: {
        // ... Getters
    },
    actions: {
        // ... Actions
        addToArray({commit}, value){
            commit('addToArray', value)
        },
        deleteFromArray({commit}, value) {
            commit('deleteFromArray', value)
        },
    },
    mutations: {
        // ... Mutations
        addToArray(state, payload){
            state.array.push(payload)
        },
        deleteFromArray(state, payload) {
            // Initial state.array: [1,2,3,4,5], lenght: 5
            let arr = []
            for (let ar of state.array) {
                // Payload = 5
                if (ar !== payload) {
                    arr.push(ar)
                }
            }
            // New arr = [1,2,3,4]
            state.array = arr
            console.log(state.array)
            // Output: state.array: [1,2,3,4], length: 4
        },
    },
}

So initially this array has a length of 5, deleteFromArray decrement array's length down to 4 (everything working fine until here), then I update sending the axios request from the "Parent" module with the new mutated value of the array of length 4, but instead is sent with its initial value of length 5.

On the other hand, addToArray works well, and it also sends the new array value of length 6 as it's expected.

I can't really see what is happening here. I've also tried a different way of removing from the array with splice(), and it works in the local state, but mutation doesn't seem to be caught from the "Parent" module, again, only on array subtraction.

Upvotes: 0

Views: 442

Answers (0)

Related Questions