Redux: Conditional Statement in the Reducer?

I’m doing the core concepts in Redux right now, and part of the tutorials say that reducers should be “pure” without side-effects. However, in the final exercise (reduxRoad) we are asked to calculate how many supplies are needed to travel for ‘x’ amount of days. We would return the original state if not enough supplies are on hand. So I’m fairly certain this required a conditional inside the case ‘travel’ statement. Is this allowed or does this violate the “pureness” of the reducer?

so if I do something like this:

switch (action.type) {
  case 'travel': {
    if (state.supplies - (action.payload * 20) < 0) return state
    else return {
      ...state, updated stuff here
    }
  }
}

From the lesson:

Reducers should only calculate the new state value based on the state and action arguments.

That reducer is still pure. Given the same inputs (state and action) it will always output the same thing. Even with a conditional inside it, the same inputs will always cause it to go down the same path in the conditional.

Ok that makes sense then. Thanks for the clarification.

1 Like