Adding a Reducer to a Redux Application
In the previous lesson, we created the UserReaction
component so that each product also had user reactions. Now we need to write a reducer that will process the reaction counter when the user clicks on a button of a particular reaction.
Let's open our product app, and in it the productsSlice.js
file with all the reducers. Now in the reducers
property, let's create another reducer reactionClicked
(we can put it first - before productAdded
, although it doesn't matter). As usual, let's pass it the state
and action
parameters:
reactionClicked(state, action) {},
Now, inside the curly braces that we left empty in the previous step, we'll write the code for it. First, we'll extract the product id from the payload
object action
and the reaction name:
const { productId, reaction } = action.payload
Then from the passed state we get the required product:
const currentProduct = state.find(product => product.id === productId)
And if such a product exists, then we increase the value of the transferred reaction by 1
:
if (currentProduct) {
currentProduct.reactions[reaction]++
}
That's it, our code for reactionClicked
is ready:
reactionClicked(state, action) {
const { productId, reaction } = action.payload
const currentProduct = state.find(product => product.id === productId)
if (currentProduct) {
currentProduct.reactions[reaction]++
}
},
Let's add an export of the resulting action creator at the end of the file:
export const {
reactionClicked,
productAdded,
productUpdated
} = productsSlice.actions
There are two important things to note here. As you may remember from previous tutorials, you can't directly update the value in your reducer code like this (look at this line: reactions[reaction]++
), but we can get away with it because we do it inside createSlice
, which uses the Immer library. It will take care of refactoring our code into a "safe" value update. This allows us to write complex things in a simpler way.
The next thing to remember is that the action
object should contain the minimum amount of information possible - just enough to indicate what happened. You shouldn't do any calculations in it. All calculations for updating the state should be done in the reducer, where you can write as much logic for this as you need.
Open your students app and in the studentsSlice.js
file, add another voteClicked
reducer to the reducers
field as shown in the tutorial. Write the code for it. The job of your reducer is to increase the vote
(or vote) value clicked for a given student by 1
on click.
At the end of the file, don't forget to export the resulting action creator voteClicked
.