Preserve State by Combining Multiple Jotai Atoms into One Atom

Daishi Kato
InstructorDaishi Kato
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years 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.

egghead
egghead
~ 17 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today