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.
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 3. Kapittel 11
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Suggested prompts:
Still meg spørsmål om dette emnet
Oppsummer dette kapittelet
Vis eksempler fra virkeligheten
Awesome!
Completion rate improved to 1.96
Challenge: Reducer
Sveip for å vise menyen
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.
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 3. Kapittel 11