From 2c7c0ffbe1ecdab03b912508ca4410fc65e1f242 Mon Sep 17 00:00:00 2001 From: JuliusKoronciCH <165957874+JuliusKoronciCH@users.noreply.github.com> Date: Tue, 21 May 2024 15:47:01 +0200 Subject: [PATCH] fix: useIsHydrated race condition fix on later call of the hook (#19) Co-authored-by: Julius Koronci --- lib/event-store.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/event-store.ts b/lib/event-store.ts index 58a0a4e..6fe16cc 100644 --- a/lib/event-store.ts +++ b/lib/event-store.ts @@ -102,6 +102,7 @@ export function createEventStore( }; const state$ = new BehaviorSubject(initialState); + const hydrationState$ = new BehaviorSubject(false); globalEventStore$ .pipe( @@ -131,6 +132,19 @@ export function createEventStore( ) .subscribe(state$); + globalEventStore$.pipe(scan((state, event) => { + if ( + event.type === '@@INIT' || + event.type === '@@RESET' + ) { + return false; + } + if (event.type === '@@HYDRATED') { + return true; + } + return state; + }, false)).subscribe(hydrationState$); + options ?.hydrator?.() .then((payload) => { @@ -234,7 +248,7 @@ export function createEventStore( }, []); }; const useIsHydrated = () => { - const [isHydrated, setIsHydrated] = useState(false); + const [isHydrated, setIsHydrated] = useState(hydrationState$.getValue()); useEffect(() => { const subscription = getHydrationObservable$().subscribe({ next: () => {