Skip to content

Commit

Permalink
refactor: avoid ternary operators and rename variables
Browse files Browse the repository at this point in the history
  • Loading branch information
yf-yang committed Oct 27, 2023
1 parent 2bbe0d4 commit 6cac845
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
15 changes: 9 additions & 6 deletions src/utils/useAtomsDebugValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ export const useAtomsDebugValue = (options?: Options) => {
const enabled = options?.enabled ?? __DEV__;
const store = useStore(options);
const [atoms, setAtoms] = useState<Atom<unknown>[]>([]);
const deferAtomSetActions = useRef(true);
deferAtomSetActions.current = true;
const duringReactRenderPhase = useRef(true);
duringReactRenderPhase.current = true;
useLayoutEffect(() => {
deferAtomSetActions.current = false;
duringReactRenderPhase.current = false;
});
useEffect(() => {
const devSubscribeStore: Store['dev_subscribe_store'] =
Expand All @@ -64,9 +64,12 @@ export const useAtomsDebugValue = (options?: Options) => {
const callback = () => {
const deferrableAtomSetAction = () =>
setAtoms(Array.from(store.dev_get_mounted_atoms?.() || []));
deferAtomSetActions.current
? Promise.resolve().then(deferrableAtomSetAction)
: deferrableAtomSetAction();
if (duringReactRenderPhase.current) {
// avoid set action when react is rendering components
Promise.resolve().then(deferrableAtomSetAction);
} else {
deferrableAtomSetAction();
}
};
// FIXME replace this with `store.dev_subscribe_store` check after next minor Jotai 2.1.0?
if (!('dev_subscribe_store' in store)) {
Expand Down
15 changes: 9 additions & 6 deletions src/utils/useAtomsSnapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ export function useAtomsSnapshot({
dependents: new Map(),
}));

const deferAtomSetActions = useRef(true);
deferAtomSetActions.current = true;
const duringReactRenderPhase = useRef(true);
duringReactRenderPhase.current = true;
useLayoutEffect(() => {
deferAtomSetActions.current = false;
duringReactRenderPhase.current = false;
});

useEffect(() => {
Expand Down Expand Up @@ -123,9 +123,12 @@ export function useAtomsSnapshot({
prevDependents = dependents;
const deferrableAtomSetAction = () =>
setAtomsSnapshot({ values, dependents });
deferAtomSetActions.current
? Promise.resolve().then(deferrableAtomSetAction)
: deferrableAtomSetAction();
if (duringReactRenderPhase.current) {
// avoid set action when react is rendering components
Promise.resolve().then(deferrableAtomSetAction);
} else {
deferrableAtomSetAction();
}
};
const unsubscribe = devSubscribeStore?.(callback, 2);
callback({} as any);
Expand Down

0 comments on commit 6cac845

Please sign in to comment.