Persist Middleware
See original GitHub issueI’m working on a middleware that saves states into LocalStorage. I see that other people also had the same idea (#7).
I have an example working, but I’d love to learn if there is a better approach.
const isBrowser = typeof window !== "undefined"
const persistedState =
isBrowser
? JSON.parse(localStorage.getItem("sidebarState"));
: null
const persist = config => (set, get, api) =>
config(
args => {
set(args);
isBrowser && localStorage.setItem("sidebarState", JSON.stringify(get()));
},
get,
api
);
const [useSidebar] = create(
persist(set => ({
isOpen: persistedState ? persistedState.isOpen : true,
toggleSidebar: () => {
set(state => ({ ...state, isOpen: !state.isOpen }));
},
}))
);
Issue Analytics
- State:
- Created 4 years ago
- Comments:13 (1 by maintainers)
Top Results From Across the Web
Persist middleware - Zustand Documentation
The persist middleware enables you to store your Zustand state in a storage (e.g. localStorage , AsyncStorage , IndexedDB , etc.
Read more >redux-persist-middleware - npm
Creates Redux middleware that will lazily persist data from certain reducers, when certain actions occur.. Latest version: 1.0.1, ...
Read more >HenrikJoreteg/redux-persist-middleware - GitHub
Creates Redux middleware that will lazily persist data from certain reducers, when certain actions occur. - GitHub - HenrikJoreteg/redux-persist-middleware: ...
Read more >redux-persist-middleware - npm package - Snyk
What is redux-persist-middleware? ... Creates Redux middleware that will lazily persist data from certain reducers, when certain actions occur. Visit Snyk Advisor ...
Read more >Persist state with Redux Persist using Redux Toolkit in React
When using Redux Persist without using the Thunk middleware, we'd get an error in the browser's console reading a non-serializable value was ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Edit: Since v3.1.4 a build-in middleware has been added, see this section of the readme for more info.
I made a pretty basic one, but it does the job.
The
persist
middleware will automatically rehydrate your state. No need to do anything specific in your state creator function 🎉In my example everything is in one file, but you can (and I do) put the
persist
andisRunningInBrowser
functions in a specific file, then import it whenever you need to use a persistent store. And it’s also Typescript friendly.@marcoacierno using your example and I still get a console error
Text content did not match. Server: "1 count" Client: "3 count"
. Using Next.js