Onyx
Onyx

Reputation: 5762

Is it wrong to set value of Vuex property from inside an action instead of through mutation?

I have a Vuex action which makes a GET request and then sets the value of a Vuex property to the response:

async getUserServers({commit, state, dispatch}, userId){
    try {
        let response = await axios.get("/servers/" + userId)
        state.servers = response.data.servers
    } catch (error) {
        console.log(error)
    }
}

As you can see, I don't use a mutation to set the state to my response, however, I read on the documentation that every change to the state should be done through mutation. I guess I have to change it to this:

async getUserServers({commit, state, dispatch}, userId){
    try {
        let response = await axios.get("/servers/" + userId)
        commit('setServers', response.data.servers)
    } catch (error) {
        console.log(error)
    }
}

I'm curious whether the first snippet of code would lead to some problems down the road.

Upvotes: 2

Views: 87

Answers (1)

Husam Elbashir
Husam Elbashir

Reputation: 7177

Mutations synchronously commit changes to the state allowing you to reliably track state changes over time through the Vue devtools. When you allow the state to be mutated by actions you might get into a situation where more than one action is mutating the same piece of state asynchronously which can make things difficult to debug.

Upvotes: 2

Related Questions