Skip to content

Commit

Permalink
fix(react): useObservablesProxy calls setState during a render
Browse files Browse the repository at this point in the history
  • Loading branch information
divdavem committed Nov 20, 2024
1 parent de19c38 commit c801b33
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions react/headless/src/utils/stores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export function useObservablesProxy<State>(stores: {[K in keyof State & string a
const internalState = useMemo(() => {
const internalState = {
hasEffect: false,
notified: true,
storeInfo: {} as Record<string, {unsubscribe: null | (() => void)}>,
checkStoreSubscribed: (key: string) => {
const store = (stores as any)[`${key}$`];
Expand All @@ -49,9 +50,15 @@ export function useObservablesProxy<State>(stores: {[K in keyof State & string a
internalState.storeInfo[key] = storeInfo;
}
if (internalState.hasEffect && !storeInfo.unsubscribe) {
storeInfo.unsubscribe = store.subscribe(() => {
triggerRerender({});
let sync = true;
storeInfo.unsubscribe = store.subscribe(async () => {
if (!sync && !internalState.notified) {
internalState.notified = true;
await Promise.resolve();
triggerRerender({});
}
});
sync = false;
}
}
return store;
Expand All @@ -68,6 +75,7 @@ export function useObservablesProxy<State>(stores: {[K in keyof State & string a
};
return internalState;
}, []);
internalState.notified = false;
useEffect(() => {
internalState.hasEffect = true;
for (const key of Object.keys(internalState.storeInfo)) {
Expand Down

0 comments on commit c801b33

Please sign in to comment.