Undo Actions on State by Implementing an undoHistory Feature with Jotai Atoms

InstructorDaishi Kato

Share this video with your friends

Send Tweet

Often times you'll want the user of your application to be able to undo an action that they've taken. Adding this feature requires you to keep track of the actions that have occurred and what state the application was in at each action.

To solve this, you'll need to store the history in some way. With Jotai, because the atoms that you are using are immutable you can save a snapshot of an atom when an action is taken and store that for use later on.

We will replace the previous shapesAtomsAtom that stored the array of our svg shapes with a historyAtom that will add each snapshot of the canvas to an array. We can then export a new shapesAtomsAtom that will behave exactly like the previous one as well as a saveHistoryAtom that we can use when we update our state. This will allow implementing an undoHistory atom that will remove any shapes or colors that we don't want to use on our canvas.