Skip to content

Commit

Permalink
feat(effects): add optional logging for the take #987
Browse files Browse the repository at this point in the history
  • Loading branch information
artalar committed Dec 30, 2024
1 parent 5231d20 commit c57b83a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
7 changes: 7 additions & 0 deletions packages/effects/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,13 @@ const someRequest = reatomRequest<{ data: Data } | { error: string }>()
const { data } = await take(ctx, someRequest, (ctx, payload, skip) => ('error' in payload ? skip : payload))
```

Note that you can increase your debug experience by passing debug name in the four parameter.

```ts
const a = await take(ctx, someAtom, (ctx, data) => data.a, 'a')
const b = await take(ctx, bAtom, undefined, 'b')
```

### takeNested

Allow you to wait all dependent effects, event if they was called in the nested async effect or by [spawn](#spawn).
Expand Down
12 changes: 11 additions & 1 deletion packages/effects/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,14 @@ export const take = <T extends Atom, Res = AtomReturn<T>>(
ctx: Ctx,
anAtom: T,
mapper: Fn<[Ctx, Awaited<AtomReturn<T>>, skip], Res | skip> = (ctx, v: any) => v,
name?: string,
): Promise<Awaited<Res>> => {
name &&= `${ctx.cause.proto.name}.${name}`

const cleanups: Array<Fn> = []

if (name) action(name)(ctx)

return new Promise<Awaited<Res>>((res: Fn, rej) => {
cleanups.push(
onCtxAbort(ctx, rej) ?? noop,
Expand All @@ -160,9 +166,13 @@ export const take = <T extends Atom, Res = AtomReturn<T>>(
if (anAtom.__reatom.isAction) state = state[0].payload
const value = await state
const result = mapper(ctx, value, skip)
if (result !== skip) res(result)
if (result !== skip) {
res(result)
if (name) action<any>(`${name}.resolve`)(ctx, result)
}
} catch (error) {
rej(error)
if (name) action<any>(`${name}.reject`)(ctx, error)
}
}),
)
Expand Down

0 comments on commit c57b83a

Please sign in to comment.