Exercises
Alright, let's get some practice with Immer!
Gradient Generator
Below, you'll find our previous solution for the Gradient Generator, using useReducer
. Your job is to update it to use Immer.
Acceptance Criteria:
- You should use the
produce
function from Immer to produce the new state, within thereducer
function - Tweak the state-updating logic to edit the draft state using mutation, instead of returning a new state object.
- The import has already been provided for you, just under the
React
import.
Code Playground
Solution:
Todo List
Let's update our “Todo List” application to use Immer.
Acceptance Criteria:
- The reducer should be updated so that Immer is used to update the state
- Go through each action, and see if we can simplify the state-updating logic using mutation. It's up to you to decide what will work best in each situation!
- Feel free to edit things beyond the reducer, eg. to change which data gets passed through in the action.
Code Playground
Solution:
Correction: As I mentioned in the “useReducer” lesson, reducers should be pure functions. As a result, we shouldn't be generating the unique ID within the reducer. The solution below has been updated, so that the ID is passed in through the action:
Pizza Toppings
Below, you'll find a pizza ordering form. All of the UI is done, but there isn't any state management yet. Your mission is to manage the state using useReducer
and Immer.
Acceptance Criteria:
- When the user submits the form, a
window.alert
should show us what size and toppings they've selected. - The radio buttons and checkboxes should be controlled by the reducer's state.
- The “Select All” button should add all of the toppings.
- If all of the toppings are selected, however, the button label should flip to "Remove All", and it should toggle all of the toppings off.
This is a challenging exercise. You'll need to figure out how to bind the values of checkboxes/radio buttons to reducer state, which is not something we've explicitly covered! The “Input Cheatsheet” should get you 75% of the way there, but you'll need to do some experimenting to figure it out.
Code Playground
Solution:
Correction: There is a more semantic way to prevent the “Select All” button from submitting the form: we can add type="button"
. That way, we don't need the event.preventDefault()
. This improvement has been added to the solution code: