Add the Reducer Logic
Get the project source code below, and follow along with the lesson material.
Download Project Source CodeTo set up the project on your local machine, please follow the directions provided in the README.md
file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.
Lesson Transcript
[00:00 - 00:13] Add the reducer logic. Go to SRC, root reducer TS, define the initial state, const initial state, that type should be root state, and then we define current.
[00:14 - 00:21] Stroke, an object with points, empty array, and color, black. Strokes should be empty array.
[00:22 - 00:33] Remove the root state type that we defined here, and import root state from the utils type. Now we can't use an empty object for the initial state, so we use initial state that we've just defined.
[00:34 - 00:48] Remove the type action that we had here, and import the actions from the actions module. Now instead of just returning state, use switch on action type, and add a default case, where you'll return state.
[00:49 - 01:06] Let's define the logic for processing actions. First, let's add the begin stroke case, begin stroke, here we return an object created from the old state, and we update the current stroke to contain the action payload in the points array.
[01:07 - 01:23] Next, define the update stroke case update stroke. Here we return a new state where current stroke has everything from the old current stroke, but the points now contain the action payload on top of the old current stroke points.
[01:24 - 01:49] And now let's define the end stroke case and stroke if there is no state current stroke points length, so if the current stroke is empty, then we return state without changing it. Otherwise, we return a new state where current stroke has the points field reset to an empty array, and the strokes has the current stroke added to the previous strokes.
This lesson preview is part of the Fullstack React with TypeScript Masterclass course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to Fullstack React with TypeScript Masterclass, plus 70+ \newline books, guides and courses with the \newline Pro subscription.
![Thumbnail for the \newline course Fullstack React with TypeScript Masterclass](/_next/image?url=https%3A%2F%2Fs3.amazonaws.com%2Fassets.fullstack.io%2Fn%2F20220425171607321_CoverImage_FSReactWTypeScript_Masterclas.png&w=3840&q=75)