Search⌘ K
AI Features

Exercise Solution: Time Counter

Explore how to solve the Redux Time Counter exercise by handling increment and decrement actions in reducers. Understand state updates, action creators, and preventing negative counter values, preparing you for more complex Redux applications ahead.

We'll cover the following...

I hope you figured out how to refactor the Counter and update changes.

Take a look at one way of doing this:

export default function(state, action) {
  switch (action.type) {
    case "SET_ACTIVE_SESSION":
      return {
        ...state,
        activeSession: action.payload
      };
    case "INCREASE_COUNTER":
      //retrieve the activeSession from the action payload
      //however this comes in all caps so convert to lower Case
      const activeSession = action.payload.toLowerCase();
      return {
        ...state,
        [activeSession]: state[activeSession] + 1
      };
    case "DECREASE_COUNTER":
      //retrieve the activeSession (called session here) from the action payload
      const session = action.payload.toLowerCase();
      return {
        ...state,
        [session]: Math.max(0, state[session] - 1)
      };
    default:
      return state;
  }
}

Once again, there isn’t much complexity in the solution.

We have a three types ...