Persist using initial state #2619
-
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 21 replies
-
|
I am having the same problem. I am following the pattern in the docs to create a store with initialization parameters and provide it through a context provider. For anyone interested in a minimal example, see here. Some details:
// [id]/page.tsx
import { Counter } from "@/components/counter";
import { CounterStoreProvider } from "@/components/provider";
type Props = {
params: {
id: string;
};
};
export default function ({ params }: Props) {
return (
<CounterStoreProvider count={Number(params.id)}>
<Counter />
</CounterStoreProvider>
);
}The persistence is keyed by the initial count // store/counter.ts
export const createCounterStore = (initState: CounterState) => {
return createStore<CounterStore>()(
persist(
(set) => ({
count: initState.count,
decrementCount: () => set((state) => ({ count: state.count - 1 })),
incrementCount: () => set((state) => ({ count: state.count + 1 })),
}),
{
name: `count-page-${initState.count}`,
storage: createJSONStorage(() => localStorage),
},
),
);
};The provider component is set up the same way in the docs. When you increase the counter and then refresh the page, the counter starts as the initial value and then quickly jumps to the stored value. Screenshare.-.2024-06-26.1_01_15.AM.mp4I tried manually rehydrate the store, but it does not work. It also seems that this only applies to dev server, in prod the counter starts straight from the storage value. |
Beta Was this translation helpful? Give feedback.
-
|
I'm having the same problem. I cannot get the initial value immediately when the page is refreshed. In this code, I have to set the editor's value and change the value when the editor updates. but I cannot get correct value for editor.
Here's the same case in a different version. 4.4.7 version
4.5.0 version
|
Beta Was this translation helpful? Give feedback.


@HermanPierre that's wrong, you should always had to handle that. There's no localStorage on server and you need to make sure that server and client first render are the same. On the client after first render you could hydrate and get the current state from the browser.