Last active
November 29, 2023 19:21
-
-
Save artalar/a20af5b96db619377c3463f1bacb07ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AsyncAction } from '@reatom/async' | |
import { Atom, atom } from '@reatom/core' | |
export const withReadyAtom = | |
<T extends AsyncAction & { dataAtom?: Atom }>(initState = false) => | |
(anAsync: T): T & { readyAtom: Atom<boolean> } => { | |
// use `spy` to prevent any race conditions | |
const readyAtom = atom((ctx, state?: boolean) => { | |
// trigger connection to start the fetch if `onConnect` used | |
if (anAsync.dataAtom) ctx.spy(anAsync.dataAtom) | |
const pending = ctx.spy(anAsync.pendingAtom) | |
return state === undefined ? initState : pending === 0 | |
}, `${anAsync.__reatom.name}.readyAtom`) | |
// grand correct state even for unconnected atom | |
anAsync.pendingAtom.onChange((ctx) => { | |
ctx.get(readyAtom) | |
}) | |
return Object.assign(anAsync, { readyAtom }) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment