Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Reducer | Redux Toolkit
Expert React

bookChallenge: 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

  1. Open the goalReducer.js file.
  2. Create the reducer using the createReducer function from the @reduxjs/toolkit package. This function simplifies the process of creating reducers.
  3. Set the initial state of the goals to an empty array ([]).
  4. Inside the createReducer function, specify the cases for different actions using the actions created in the goalAction.js file.
  5. For adding a goal, use the .addCase method and pass in the addGoal action as the first argument. In the corresponding callback function, update the state by pushing the action.payload (the goal) into the state array.
  6. For removing a goal, use the .addCase method and pass in the removeGoal 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 matching goal.id from the state array.

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 11

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Suggested prompts:

Ask me questions about this topic

Summarize this chapter

Show real-world examples

Awesome!

Completion rate improved to 1.96

bookChallenge: Reducer

Swipe to show menu

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

  1. Open the goalReducer.js file.
  2. Create the reducer using the createReducer function from the @reduxjs/toolkit package. This function simplifies the process of creating reducers.
  3. Set the initial state of the goals to an empty array ([]).
  4. Inside the createReducer function, specify the cases for different actions using the actions created in the goalAction.js file.
  5. For adding a goal, use the .addCase method and pass in the addGoal action as the first argument. In the corresponding callback function, update the state by pushing the action.payload (the goal) into the state array.
  6. For removing a goal, use the .addCase method and pass in the removeGoal 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 matching goal.id from the state array.

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 11
some-alt