Course Content
Expert React
Expert React
4. Formik
6. Next Steps
Challenge: Reducer
Step 3: Create reducer
Focus on creating a reducer to handle dispatched actions and update the goals state in the Redux store. Reducers are pure functions that specify how the state should change in response to actions.
Example
Challenge
- Open the
goalReducer.js
file. - Create the reducer using the
createReducer
function from the@reduxjs/toolkit
package. This function simplifies the process of creating reducers. - Set the initial state of the goals to an empty array (
[]
). - Inside the
createReducer
function, specify the cases for different actions using the actions created in thegoalAction.js
file. - For adding a goal, use the
.addCase
method and pass in theaddGoal
action as the first argument. In the corresponding callback function, update the state by pushing theaction.payload
(the goal) into the state array. - For removing a goal, use the
.addCase
method and pass in theremoveGoal
action as the first argument. In the corresponding callback function, update the state by returning a new array that filters out the goal with the matchinggoal.id
from the state array.
Everything was clear?