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:
- We use the equals sign
=
to supply a default value for thestate
parameter. - We use the spread operator (
...
) to copy the current state and any changed values into a new object, not the existingstate
argument. We’ll explain why in the next exercise.
Instructions
Let’s start building a reducer for our playlist application. For this first checkpoint, it should:
- Be named
reducer
- Accept
state
andaction
arguments - Default
state
toinitialState
if no value is provided - Use a switch statement on the
action.type
property - Always return
state
as thedefault
case
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' }
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' }