Preserve State by Combining Multiple Jotai Atoms into One Atom

Daishi Kato
InstructorDaishi Kato

Share this video with your friends

Send Tweet
Published a year ago
Updated 11 months ago

In the previous lessons, we’ve been able to create and render shapes by storing the data needed into a Jotai atom. You’ll notice that each time you draw a path that the previous path is cleared. This is because we are setting the new path in the old path’s place, it's gone forever.

We can preserve state by aggregating atoms into another single atom by pushing them into an array. Once we have this array, we can map over the array in a new component to draw as many paths as you would like

Daishi Kato: [0:00] So far, we have one path to draw. To draw a multiple path, we make a new file SvgShapes.tsx. We use a new concept, atoms in atom. This atom is named shapeAtomsAtom. It's an atom whose value is a list of atom configs.

[0:23] Let's modify SvgShape.tsx. Instead of using the atom globally defined, the component receives a shapeAtom as a prop and uses it. The global atom in this file is no longer needed. We export createShapeAtom helper function that can be used in the new file.

[0:45] Going back to SvgShapes.tsx, import it. Define addShapeAtom. This will create a new shapeAtom and add it into the list in shapeAtomsAtom. SvgShapes is a new component that loops over the shapeAtom list in shapeAtomsAtom.

[1:06] We use map to render SvgShape for each shapeAtom. It's important to note that an atom config can be converted to a string which can be used for the key in the map. Finally, we make SvgDots to use the new addShapeAtom and SvgRoot to use the new SvgShapes. As you can see, we are now able to draw multiple paths.

[1:33] Let's recap what we did. The most important one is shapeAtomsAtom, which is an atom whose value is a list of atom configs. SvgShapes component uses the atom, maps over the list, and passes a shapeAtom as a prop to SvgShape. Then, SvgShape component receives the shapeAtom and uses it to draw a path.