Skip to content

How to restore persisted state on page refresh #1569

Answered by shellking4
shellking4 asked this question in General
Discussion options

You must be logged in to vote

Hey I figured out my issue has to do with hydration, since I'm using an async storage. Looked up in the docs and found a solution to my problem.
Here is my solution

// use-hydration.ts
import { useEffect, useState } from 'react';
import { StoreApi, UseBoundStore, } from 'zustand'
import { StorePersist, Write } from 'zustand/middleware';

export const useHydration = (boundStore: UseBoundStore<Write<StoreApi<any>, StorePersist<any, unknown>>>) => {
    const [hydrated, setHydrated] = useState(boundStore.persist.hasHydrated);
    useEffect(() => {
        const unsubHydrate = boundStore.persist.onHydrate(() => setHydrated(false))
        const unsubFinishHydration = boundStore.persist.onFini…

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by shellking4
Comment options

You must be logged in to vote
1 reply
@dai-shi
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants