Hely Saul Oberto
Hely Saul Oberto

Reputation: 597

React useReducer sets the whole state as undefined

I'm having a problem where updating my Context state with a reducer, sets the whole state as undefined... This is my code:

const [state, dispatch] = useReducer(AccountReducer, initialState);

The call to the Dispatch

 dispatch({
  type: SET_TOKEN,
  payload: token
})

And the reducer

  const AccountReducer = (state, action) => {
   switch (action.type) {
    case SET_TOKEN:
      return {
        ...state,
        token: action.payload
      }

    default:
      break
  }
};

After I make the dispatch the whole state is set to undefined.... Any ideas on why this is happening?

Upvotes: 0

Views: 823

Answers (1)

Brian Thompson
Brian Thompson

Reputation: 14355

A reducer must return the new state value each time it is called. In your default case you return nothing (undefined), which will be your next state.

Simply return the last state in the default case:

 const AccountReducer = (state, action) => {
   switch (action.type) {
    case SET_TOKEN:
      return {
        ...state,
        token: action.payload
      }

    default:
      return state; // Return the same value passed in to be used as the next state
  }
};

I'm working under the assumption that SET_TOKEN is a variable shared between the dispatch call and the reducer. If they do not match, this will also cause problems.

Upvotes: 1

Related Questions