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](/content/images/size/w1200/2024/04/Persistent-State-1.png)
Requirements
- Make sure Jotai is installed
npm i jotai
- 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)