Skip to content

Instantly share code, notes, and snippets.

@artalar
Last active November 29, 2023 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artalar/a20af5b96db619377c3463f1bacb07ff to your computer and use it in GitHub Desktop.
Save artalar/a20af5b96db619377c3463f1bacb07ff to your computer and use it in GitHub Desktop.
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