Skip to content

Commit

Permalink
feat(hooks): add isInit method
Browse files Browse the repository at this point in the history
  • Loading branch information
artalar committed Oct 21, 2023
1 parent a9f71ae commit 5138685
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions packages/hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
atom,
Atom,
AtomCache,
AtomProto,
AtomState,
Ctx,
CtxSpy,
Expand Down Expand Up @@ -46,7 +47,10 @@ export const withInit =

export const onConnect = (
anAtom: Atom,
cb: Fn<[Ctx & { controller: AbortController; isConnected(): boolean }], (() => void) | unknown>,
cb: Fn<
[Ctx & { controller: AbortController; isConnected(): boolean }],
(() => void) | unknown
>,
): Unsubscribe => {
const connectHook = (ctx: Ctx) => {
const controller = new AbortController()
Expand Down Expand Up @@ -124,13 +128,16 @@ const _onUpdate: {
}

export const onUpdate: typeof _onUpdate = (anAtom: Atom, cb = noop) =>
((anAtom as Atom & { deps?: Array<Atom> }).deps ?? []).reduce((acc, dep) => {
const un = onUpdate(dep, (ctx) => ctx.get(anAtom))
return () => {
un()
acc()
}
}, _onUpdate(anAtom, cb) as Unsubscribe)
((anAtom as Atom & { deps?: Array<Atom> }).deps ?? []).reduce(
(acc, dep) => {
const un = onUpdate(dep, (ctx) => ctx.get(anAtom))
return () => {
un()
acc()
}
},
_onUpdate(anAtom, cb) as Unsubscribe,
)

/** @deprecated use the second parameter of `ctx.spy` instead */
// @ts-ignore
Expand Down Expand Up @@ -182,3 +189,12 @@ export const isConnected = (ctx: Ctx, { __reatom: proto }: Atom) =>
const cache = proto.patch ?? read(proto)
return !!cache && cache.subs.size + cache.listeners.size > 0
})

const initSetAtom = atom(
(ctx, state = new WeakSet<AtomProto>()) => state,
'initSetAtom',
)
export const isInit = (ctx: Ctx) => {
const set = ctx.get(initSetAtom)
return set.has(ctx.cause.proto) ? false : !!set.add(ctx.cause.proto)
}

1 comment on commit 5138685

@vercel
Copy link

@vercel vercel bot commented on 5138685 Oct 21, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.