question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Persist Middleware

See original GitHub issue

I’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:closed
  • Created 4 years ago
  • Comments:13 (1 by maintainers)

github_iconTop GitHub Comments

16reactions
AnatoleLucetcommented, Dec 8, 2021

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.

import create, { GetState, SetState, StateCreator, StoreApi } from "zustand";

type Product = { id: number; amount: number };

interface Store {
  products: Product[];
  setProducts: (payload: Product) => void;
}

const isRunningInBrowser = () => typeof window !== "undefined";

const persist = <T>(name: string, config: StateCreator<T>) => (
  set: SetState<T>,
  get: GetState<T>,
  api: StoreApi<T>,
): T => {
  const state = config(
    (payload) => {
      set(payload);

      if (isRunningInBrowser) {
        localStorage.setItem(name, JSON.stringify(payload));
      }
    },
    get,
    api,
  );

  return {
    ...state,
    ...(isRunningInBrowser() && JSON.parse(localStorage.getItem(name))),
  };
};

export const [useShoppingCart] = create<Store>(
  persist<Store>("shoppingCart", (set, get) => ({
    products: [],
    setProducts: (payload) => {
      const state = get();

      set({ ...state, products: [...state.products, payload] });
    },
  })),
);

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 and isRunningInBrowser functions in a specific file, then import it whenever you need to use a persistent store. And it’s also Typescript friendly.

4reactions
maxwaiyakicommented, Aug 23, 2020

@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

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found