How to persist React global state in Index DB with Jotai

Learn to persist React state using Jotai & IndexedDB. This guide offers a seamless solution for state storage in IndexDB.

How to persist React global state in Index DB with Jotai

Requirements

  1. Make sure Jotai is installed
npm i jotai
  1. Install IDB-Keyval
npm i idb-keyval

Setup

import { atomWithStorage, createJSONStorage } from 'jotai/utils'
import { get, set, del } from 'idb-keyval'

const storage = createJSONStorage(() => ({
  getItem: async (name: string): Promise<string | null> => {
    return (await get(name)) || null
  },
  setItem: async (name: string, value: string): Promise<void> => {
    await set(name, value)
  },
  removeItem: async (name: string): Promise<void> => {
    await del(name)
  },
}))

const myAtom = atomWithStorage("my-atom", <value>, storage)

Subscribe to Victor Nwanguma

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe