1.2.13 • Published 1 year ago
zustand-persist-cookie-storage v1.2.13
zustand-persist-cookie-storage
A simple package created to allow persisting a zustand store to a cookie 🙂. The package will automatically apply an expiry for the cookie as far in the future as possible (you can override this if you want).
Install
pnpm add zustand-persist-cookie-storage
pnpm add -D @types/js-cookieUsage
- Import the package using
import CookieStorage from 'zustand-persist-cookie-storage'. - Import
createJSONStoragefrom zustand usingimport { createJSONStorage } from 'zustand/middleware'. - Create your store normally.
- In the persist options, set
storagetostorage: createJSONStorage(() => CookieStorage()). - Pass any cookie options to
CookieStorage.
Your code should look something like:
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import CookieStorage from 'zustand-persist-cookie-storage';
export const usePersistedZustandStore = create(
persist(
...,
{
name: ...,
storage: createJSONStorage(() => CookieStorage({...[COOKIE OPTIONS GO HERE]}))
}
)
);Cookie Options
The type of cookie options should match CookieAttributes from @types/js-cookie (see @types/js-cookie for more info).