SSR issues with Next.js (and persisting the data)
See original GitHub issueHi there,
I am loving the way that Zustand works and absolutely enjoy using it, but unfortunately I have issues with the following scenario:
- I have a “user store” that is a Zustand store that saves the “selected user ID”.
- I have a couple of buttons that allows me to select a specific user (but the ID only) and saves it into the store.
Then I am trying to display the selected user based on the ID that is stored in the store. Through a array.find()
, where I loop through my users array. Everything works fine so far, but as soon as I want to display a property from that selected user, I get the following error when I refresh the page:
This error only happens whenever I refresh the page so it must be an issue with the “persist data” functionality. I have made a Codesandbox to reproduce this issue and I hope someone is able to help me out with this.
https://codesandbox.io/s/nextjs-zustand-example-z8ujs?file=/pages/index.tsx
Thanks a lot and I hope someone is able to help me out.
Edit: Apparently this issue doesn’t even come from the part that filters the users based on the ID. It also throws the error in the console from only showing the “selected user ID” directly from the store, that is persisted. Really strange issue.
Issue Analytics
- State:
- Created 3 years ago
- Comments:18
Top GitHub Comments
@UlisseMini as shown in the doc, this is intentional.
One way to get the behavior you want is to use an asynchronous storage. You could create your own reusable persist async middleware by promisifying your storage (as shown here) :
@sandren ah, my bad. This part: “it can be done with a simple condition based on this persist option” is wrong. I thought it’d be sufficient, but apparently it isn’t. I’ve forked @gino’s csb: https://codesandbox.io/s/nextjs-zustand-example-forked-bnpfz?file=/pages/index.tsx The trick is the
useHasHydrated
hook. If you conditionally render elements based on your store using this hook, you won’t have the warning.