Зміст курсу
Redux Toolkit & React
Redux Toolkit & React
Challenge: Creating Reducer
Step 3
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.
- The
createReducer
function simplifies the process of creating reducers by providing a convenient syntax. - Use the
.addCase
method of thebuilder
object to specify the cases for different actions. - Access the payload of the action using
action.payload
.
Дякуємо за ваш відгук!