Delete Data in a Jotai Atom by Composing and Filtering Atoms

Daishi Kato
InstructorDaishi Kato

Share this video with your friends

Send Tweet
Published a year ago
Updated 11 months ago

We will look at how to delete a shape that we have stored in an array. You'll see how we can continue building functionality by composing atoms together to achieve what we want.

For this feature, we will need to create a few atoms to add the functionality needed. We will start by creating selectedAtom and unselectAtom. selectedAtom is a getter for the selected Shape and unselectAtom will be used to clear the selection when an atom is deleted.

When these two functions are set, we can create a deleteSelectedShapeAtom which will filter out the selected atom that is held in shapeAtomsAtom. And finally, we'll wire this up to a button to actually use!

Daishi Kato: [0:00] If we draw shapes, the shape attribute's stored in an array. We wanted to read one from the array. First, define two new atoms in selection.ts. selectedAtom is in an atom that returns [?] calling the selected atom config or null if nothing is selected. unselectAtom is in an atom to clear the selection. In SvgShapes.tsx, we import those two atoms.

[0:30] Define deleteSelectedShapeAtom. If there's a selected shape, it will remove it from the array stored in shapeAtom atom. What is important here is this is just the leading atom config from the array, which is actually null. Internally, the atom value is stored in a WeakMap. It is eventually garbage collected.

[0:57] Finally, in Controls.tsx, we'll import the atom from SvgShapes.tsx. Using the atom, create a new button. Let's see how it works. We can draw shapes and delete a selected shape.

[1:14] One more trick is to disable the button if it doesn't do anything. Modify deleteSelectedShapeAtom to return a Boolean indicating if there's a selection or not. Then, use the Boolean in the Controls component and disable the button unless there's a selection. Now, the button is disabled as expected.

[1:38] In this lesson, we created a few atoms and implemented the deleting feature, which is essentially just removing an item from an array.