How to Update State in a React Reducer to Store Moved Items
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:10] update the reducer, open the upstate reducer and add the move task case to the reducer. Inside of it, we'll want to destructure the action payload like this.
[00:11 - 00:38] const, dragged, item ID, hovered, item ID, source, column ID, and target, column ID, with the structure from action payload. Then we get the source and target list indices, const source list index equals find item index by ID, we pass in draft lists and source column ID.
[00:39 - 00:47] In the similar manner, find the target list index. Instead of source column ID, just pass target column ID.
[00:48 - 01:07] After we have the source and target indices, we can find the indices for the dragged and hovered items, const drag index equals find item index by ID. And now we pass the source list, draft lists, source list index.
[01:08 - 01:16] And we want to find the dragged item ID. Similar to how we find the drag item index, find the hover index.
[01:17 - 01:29] Here we'll need to also check if there is hover item ID. And we try to find it in the target list index, hover item ID.
[01:30 - 01:38] If it doesn't exist, then we return zero without doing anything. Now we have dragged item index and hover item index.
[01:39 - 01:52] Now it's time to get the item that we're dragging and store it in the item constant. List item equals draft lists source list index tasks drag index.
[01:53 - 02:06] That's the item we're dragging. Now we remove it from the source list, draft lists source list index tasks spl ice drug index and we splice one element.
[02:07 - 02:27] And then we add this item to the target list, draft lists target list index tasks splice hover index zero item. After we moved our item, call break and launch the app yarn start.
[02:28 - 02:30] Now we should be able to drag the columns and the cards.
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)