Replies: 2 comments 2 replies
|
@sirarifarid you need a context, that's not a Zustand thing is something general that also apply to libraries like Note Per-request safe Redux store creation: A Next.js server can handle multiple requests simultaneously. This means that the Redux store should be created per request and that the store should not be shared across requests. |
0 replies
I would like to push this pattern. We need a special middleware to avoid misusing. Based on that, what you could do is something like this: 'use client';
import { create } from 'zustand';
import React from 'react';
const isSSR = typeof window === 'undefined';
// No types yet
const ssrSafe = (config: any) => (set: any, get: any, api: any) => {
if (!isSSR) {
let initialState: any;
const origGetInitialState = api.getInitialState;
api.getInitialState = () => initialState || origGetInitialState();
api.setInitialState = (update: any) => {
initialState = { ...api.getInitialState(), ...update };
};
return config(set, get, api);
}
const ssrSet = () => {
throw new Error('Cannot set state of Zustand store in SSR');
};
api.setState = ssrSet;
return config(ssrSet, get, api);
};
const useCount = create(
ssrSafe((set: any, get: any, api: any) => ({
count: 0,
initialized: false,
initialize: (count: number) => {
if (!get().initialized) {
set({ count, initialized: true });
api.setInitialState({ count, initialized: true });
}
},
}))
);
// usig server fetched value as initial value of the store
export const Client = ({ data }: { data: any }) => {
if (!isSSR) {
useCount.getState().initialize(data.count);
}
const state = useCount();
const count = isSSR ? data.count : state.count;
return <p>Client count: {count}</p>;
}; |
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Need a way to use server fetched data in store from initial state without context like
useHydratedAtomsView problem: https://stackblitz.com/edit/stackblitz-starters-zamnamsh?file=components%2Fclient.tsx
All reactions