Search code examples
javascriptvuejs2storevuex

.push end´s in "Do not mutate vuex store state outside mutation handlers"


I have defined a Vuex store with (actions, state, mutations and getters)

When i add a new todo to my state array in the mutations i got following error: Error: [vuex] Do not mutate vuex store state outside mutation handlers.

const state = {
  todos: []
}

export default {
  ADD_TODO (state, payload) {
    state.todos.push(payload.todo)
  }
}

Is it not possible to use an array with the state?

I also tried this with using an object for todos state which works fine.


Solution

  • You cannot mutate the state itself, you have to assign a new value to state to mutate it so in your case you can do :

    in your component assign your todos from store to a variable like

    //COMPONENT
    let todos = [...this.$store.todos] //or assign from a getter if you have one;
    todos.push(newTodo);
    addTodo(todos); //call mutation from component and pass your todos array as payload
    
    
    //STORE
    ADD_TODO (state, payload) {
      state.todos = payload;
    }