How to persist the data in atoms with local storage using recoil persist.

How to persist the data in atoms with local storage using recoil persist.

·

2 min read

Welcome friends 👋. In this blog post, you will learn how to persist the data in local storage in recoil.

For people, who understand Hindi %[youtu.be/HLt512RmLEM]

👁️Situation

Suppose, you are making a to-do list website where people can type todos and todos will be stored in the local storage. But the question arises, how can you persist the data with local storage.

😍Solution

Let’s take an example 👇

import { atom } from "recoil";

export const todosAtom = atom<{ id: number; title: string }[]>({
  key: "todos",
  default: [],
});

In the 👆 example, there is an atom(‘todosAtom’) that is responsible for storing all the todos.

Now, we can use effects_UNSTABLE

import { atom } from "recoil";

export const todosAtom = atom<{ id: number; title: string }[]>({
  key: "todos",
  default: [],
  effects_UNSTABLE: [
    ({ setSelf }) => {
      const todos = localStorage.getItem("todos");

      if (todos === null) {
        setSelf([]);
      } else {
        setSelf(JSON.parse(todos));
      }
    },
  ],
});

Here, we are using effects_unstable which runs when the atom is initialized or changed.

But, unfortunately, you will encounter an error if you are using an SSR framework like nextjs.

🤔Then how to solve it?

yarn add recoil-persist

recoil-persist

import { atom } from "recoil";
import { recoilPersist } from "recoil-persist";

const { persistAtom } = recoilPersist();

export const todosAtom = atom<{ id: number; title: string }[]>({
  key: "todos",
  default: [],
  effects_UNSTABLE: [persistAtom],
});

Now, all of your work would be done with the help of the recoil persist.

If you have any questions, feel free to ask here👇: Join the Next Dev Discord Server!

Did you find this article valuable?

Support Next Dev's Blog by becoming a sponsor. Any amount is appreciated!