Search code examples
reactjsreduxreact-reduxredux-toolkit

How to remove all item in state using redux toolkit


im made a Todo App using redux toolkit, and im trying to make a button which to clear all item in array;

Im try to set array to empty by using splice like this but doesn't work

clearList: (state) => {
      return state.splice(0, state.length);
    }

Does anyone know how to do it?


Solution

  • With redux-toolkit either update/mutate the state object or return the next state value, but not both.

    clearList: (state) => {
      state.splice(0, state.length);
    }
    

    or since you are just wanting to clear the array you could just return a new empty array.

    clearList: (state) => {
      return [];
    }
    

    You can read more on Direct State Mutation