State
/ API Reference / MiddlewareState
/ API Reference / Middlewarepersistence
A middleware for persisting state to storage (localStorage, sessionStorage, or custom storage).
Arguments
| Argument | Type | Description |
|---|---|---|
| key | string | The key to use for storing the state |
| getStorage | Function | A function that returns the storage object (localStorage, sessionStorage, etc.) |
| actions | Array<string>? | Optional array of action names to persist. If not provided, all actions are persisted. |
| onHydrated | Function? | Optional callback function called when state is hydrated from storage |
| encode | Function? | Optional function to encode data before storing (default: JSON.stringify) |
| decode | Function? | Optional function to decode data after retrieving (default: JSON.parse) |
Returns
(Middleware) A middleware object that can be passed to useStoreWithMiddleware or useOptimisticStoreWithMiddleware.
Example
import { useStoreWithMiddleware, persistence } from '@weser/state'
const useStore = useStoreWithMiddleware([
persistence({
key: 'my-app-state',
getStorage: () => localStorage,
}),
])
© 2024-present Robin Weser. All Rights Reserved.