diff --git a/src/LoadManager.ts b/src/LoadManager.ts index b3fd962..defc5b9 100644 --- a/src/LoadManager.ts +++ b/src/LoadManager.ts @@ -17,6 +17,16 @@ export class LoadManager { onAllLoaded(callback: () => void) { this.onAllLoadedCallback = callback + + // Possible this could be called with a custom callback *after* + // loading has finished. Which means setLoaded (below) has finished + // being called and the custom callback would never be run. + // If loading has finished, execute callback immediately. + // https://github.com/roadmanfong/zustand-persist/issues/4 + // https://github.com/roadmanfong/zustand-persist/issues/9 + if (Object.values(this.loadStatusRecord).every(Boolean)) { + this.onAllLoadedCallback() + } } setLoaded(key: string) { diff --git a/src/PersistGate.tsx b/src/PersistGate.tsx index 84eb7da..00e4f68 100644 --- a/src/PersistGate.tsx +++ b/src/PersistGate.tsx @@ -1,4 +1,4 @@ -import React, { useState } from 'react' +import React, { useEffect, useState } from 'react' import { getLoadManager } from './LoadManager' export interface PersistGateProps { @@ -11,10 +11,15 @@ export function PersistGate(props: PersistGateProps) { const { children, loading = false, onBeforeLift } = props const [isReady, setIsReady] = useState(false) - getLoadManager().onAllLoaded(async () => { - onBeforeLift && (await onBeforeLift()) - setIsReady(true) - }) + // Only need to call this once on initial render. + // https://github.com/roadmanfong/zustand-persist/issues/4 + // https://github.com/roadmanfong/zustand-persist/issues/9 + useEffect(() => { + getLoadManager().onAllLoaded(async () => { + onBeforeLift && (await onBeforeLift()) + setIsReady(true) + }) + }, []) return {isReady ? children : loading} }