Middlewares
The Persist Middleware
Section titled “The Persist Middleware”The Persist Middleware enables us to store our Zustand state in a storage (e.g. localStorage, IndexedDB, etc), thus persisting its data.
Local Storage
Section titled “Local Storage”Persist takes a stateCreatorFn and persistOptions. One of the options is name, which is a unique name of the item for our store in the storage.
interface PersonState { firstName: string; setFirstName: (value: string) => void;}
export const usePersonStore = create<PersonState>()( persist((set) => ({ firstName: "", setFirstName: (value: string) => set((state) => ({ firstName: value })), })), { name: "person-storage" },);This is the result in the local storage:
Section titled “This is the result in the local storage:”| Key | Value |
|---|---|
| person-storage | {“state”: {“firstName”:“Marlon”}} |
Session Storage
Section titled “Session Storage”Persist also receives an optional storage parameter, which is used to read and write the persisted state. Defaults to createJSONStorage(() => localStorage).
const customSessionStorage: StateStorage = { getItem: (name: string): string | Promise<string | null> | null => { return window.sessionStorage.getItem(name); }, setItem: (name: string, value: string): void | Promise<void> => { window.sessionStorage.setItem(name, value); }, removeItem: (name: string): void | Promise<void> => { window.sessionStorage.removeItem(name); },};
export const usePersonStore = create<PersonState & Actions>()( persist(storeApi, { name: "person-storage", storage: createJSONStorage(() => customSessionStorage), }),);TO BE IMPLEMENTED
Logger
Section titled “Logger”TO BE IMPLEMENTED