Sinan Samet
Sinan Samet

Reputation: 6742

How do I reset the state to its initial state?

I can't seem to reset the default state; how do I do that? I tried this but all it does is add state to state and calls it undefined.

const initialState = {
  name: null,
  coins: 0,
  image: null,
};

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case types.ADD_GROUP_COINS:
      return {
        ...state,
        coins: state.coins + action.coins
      };
    case types.DELETE_GROUP:
      return {
        state: undefined
      };
    default:
      return state;
  }
}

Upvotes: 1

Views: 2645

Answers (1)

Aurora0001
Aurora0001

Reputation: 13547

To reset the state to the initialState, simply return initialState, like this:

case types.DELETE_GROUP:
  return initialState;

Remember that in the reducer, the object that you return is the new state. You don't need to wrap it in another object, like this:

return {
    state: ...
}

That will give you a property called state in your state, which isn't at all what you need.

From the documentation:

The reducer is a pure function that takes the previous state and an action, and returns the next state.

It's easy to get confused about this, so be careful! Take a look at your default case if you're still not quite sure: you're returning the old state variable as the new state, not { state: state } which you are essentially doing with the current DELETE_GROUP handler.

Upvotes: 6

Related Questions