Conteúdo do Curso
State Management with Redux Toolkit in React
State Management with Redux Toolkit in React
2. Applying Redux Toolkit in React
What AwaitsUnderstanding the Project Code and File StructureCreating the Redux StoreIntegrating the Redux Store Into the React AppInspecting the Store in the React AppUnderstanding Actions and Action CreatorsUnderstanding the Role of ReducersInspecting Actions and Reducers in ReduxConnecting Redux with React ComponentsCompleting the App
Challenge: Implementing the 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
.
Tudo estava claro?
Obrigado pelo seu feedback!
Seção 3. Capítulo 5