How can I use zustand persist with indexeddb? #1721
-
Indexeddb can store more data than localstorage and other types of storage ? How can I use it with zustand? |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 2 replies
-
I think someone did persist+indexedeb before (but maybe with old options). |
Beta Was this translation helpful? Give feedback.
-
feel free to use this template: If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
-
From the docs, the recommended way to use indexeddb is as follow import { create } from 'zustand'
import { persist, createJSONStorage, StateStorage } from 'zustand/middleware'
import { get, set, del } from 'idb-keyval' // can use anything: IndexedDB, Ionic Storage, etc.
// Custom storage object
const storage: StateStorage = {
getItem: async (name: string): Promise<string | null> => {
console.log(name, 'has been retrieved')
return (await get(name)) || null
},
setItem: async (name: string, value: string): Promise<void> => {
console.log(name, 'with value', value, 'has been saved')
await set(name, value)
},
removeItem: async (name: string): Promise<void> => {
console.log(name, 'has been deleted')
await del(name)
},
}
export const useBoundStore = create(
persist(
(set, get) => ({
bears: 0,
addABear: () => set({ bears: get().bears + 1 }),
}),
{
name: 'food-storage', // unique name
storage: createJSONStorage(() => storage),
},
),
) |
Beta Was this translation helpful? Give feedback.
-
I attempted to follow your answer and also referenced the docs in my Nextjs 14 stack project where I use Dexie.js instead of idb-keyval. However, im unable to rehydrate the store. I always get the warning that it couldn't find the storage. |
Beta Was this translation helpful? Give feedback.
-
Here is how I use index db and zustand:
|
Beta Was this translation helpful? Give feedback.
with Remix I insure indexeddb is opened by putting in my clientLoader a code like this