zustand-persist-cookie-storage
v1.2.13
Published
Solution to persist a zustand store in a cookie.
Downloads
293
Maintainers
Readme
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-cookie
Usage
- Import the package using
import CookieStorage from 'zustand-persist-cookie-storage'
. - Import
createJSONStorage
from zustand usingimport { createJSONStorage } from 'zustand/middleware'
. - Create your store normally.
- In the persist options, set
storage
tostorage: 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).