Skip to content

Commit

Permalink
fix: useIsHydrated race condition fix on later call of the hook (#19)
Browse files Browse the repository at this point in the history
Co-authored-by: Julius Koronci <[email protected]>
  • Loading branch information
JuliusKoronciCH and Julius Koronci authored May 21, 2024
1 parent 127d8f9 commit 2c7c0ff
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/event-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ export function createEventStore<T extends object>(
};

const state$ = new BehaviorSubject<T>(initialState);
const hydrationState$ = new BehaviorSubject(false);

globalEventStore$
.pipe(
Expand Down Expand Up @@ -131,6 +132,19 @@ export function createEventStore<T extends object>(
)
.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) => {
Expand Down Expand Up @@ -234,7 +248,7 @@ export function createEventStore<T extends object>(
}, []);
};
const useIsHydrated = () => {
const [isHydrated, setIsHydrated] = useState(false);
const [isHydrated, setIsHydrated] = useState(hydrationState$.getValue());
useEffect(() => {
const subscription = getHydrationObservable$().subscribe({
next: () => {
Expand Down

0 comments on commit 2c7c0ff

Please sign in to comment.