Search code examples
javascriptvue.jsvuejs2vuex

Vuex: Erasing store state back to an empty array


I have a Vuex store state called scannedList and the initial state is []:

state: {
  scannedList: []
}

I have a mutation that pushes id's to the array. I tried to clear all the state back to an empty array with:

store.commit('addToScannedList', [])

but the id's still remain within the array. What is the proper way to accomplish this?


Solution

  • Pushing an empty array onto an array won't clear it. You can make a new mutation:

    resetScannedList(state) {
      state.scannedList = [];
    }
    

    Or you could make a condition in your existing mutation for clearing it if you don't pass a payload:

    addToScannedList(state, item) {
      if(item !== undefined) {
        state.scannedList.push(item);
      } else {
        state.scannedList = [];
      } 
    }
    

    Which you'd trigger with store.commit('addToScannedList') with no payload