Learn

So far, we’ve defined the state of our application and the actions representing requests to change that state, but we haven’t seen how these changes are carried out in JavaScript. The answer is a reducer.

A reducer, or reducer function, is a plain JavaScript function that defines how the current state and an action are used in combination to create the new state.

Here’s an example of a reducer function for a todo app:

const initialState = [ 'Print trail map', 'Pack snacks', 'Summit the mountain' ]; const todoReducer = (state = initialState, action) => { switch (action.type) { case 'todos/addTodo': { return [ ...state, action.payload]; } case 'todos/removeAll': { return []; } default: { return state; } } }

There a few things about this reducer that are true for all reducers:

  • It’s a plain JavaScript function
  • It defines the application’s next state given a current state and a specific action
  • It returns a default initial state if no action is provided
  • It returns the current state if the action is not recognized

There are two intermediate JavaScript syntaxes used here:

  1. We use the equals sign = to supply a default value for the state parameter.
  2. We use the spread operator (...) to copy the current state and any changed values into a new object, not the existing state argument. We’ll explain why in the next exercise.

Instructions

1.

Let’s start building a reducer for our playlist application. For this first checkpoint, it should:

  • Be named reducer
  • Accept state and action arguments
  • Default state to initialState if no value is provided
  • Use a switch statement on the action.type property
  • Always return state as the default case
2.

Add a case for the 'songs/addSong' action type.

If the action.type is 'songs/addSong', return a copy of the state object with the new song added.

You can expect an action like this:

{ type: 'songs/addSong', payload: 'Take Five' }
3.

Add a case for the 'songs/removeSong' action type.

If the action.type is 'songs/removeSong', return a copy of the state object with the specified song removed. Use the array filter() method.

You can expect an action like this:

{ type: 'songs/removeSong', payload: 'Respect' }

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?