From e59ef5181d5625408353c1b8ec6732e12848c608 Mon Sep 17 00:00:00 2001 From: David Maskasky Date: Sat, 25 Jan 2025 11:16:58 -0800 Subject: [PATCH] fix type and export observe utility --- package.json | 2 +- src/atomEffect.ts | 18 ++++++++++++------ src/index.ts | 1 + src/withAtomEffect.ts | 6 +++--- 4 files changed, 17 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index f37695b..f93309a 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "jotai-effect", "description": "👻🔁", - "version": "1.1.0", + "version": "1.1.1", "type": "module", "author": "David Maskasky", "contributors": [ diff --git a/src/atomEffect.ts b/src/atomEffect.ts index 152a9b5..81ee175 100644 --- a/src/atomEffect.ts +++ b/src/atomEffect.ts @@ -2,12 +2,16 @@ import type { Atom, Getter, Setter } from 'jotai/vanilla' import { atom } from 'jotai/vanilla' type Cleanup = () => void + type GetterWithPeek = Getter & { peek: Getter } + type SetterWithRecurse = Setter & { recurse: Setter } -export type Effect = Parameters[0] -export type AtomWithEffect = Atom> = T & { - effect: Effect -} + +export type Effect = ( + get: GetterWithPeek, + set: SetterWithRecurse +) => void | Cleanup + type Ref = { /** inProgress */ i: number @@ -31,7 +35,7 @@ type Ref = { export function atomEffect( effect: (get: GetterWithPeek, set: SetterWithRecurse) => void | Cleanup -): AtomWithEffect { +): Atom & { effect: Effect } { const refreshAtom = atom(0) const refAtom = atom( () => ({ i: 0 }) as Ref, @@ -119,7 +123,9 @@ export function atomEffect( setLabel(refAtom, 'ref') setLabel(baseAtom, 'base') } - const effectAtom = atom((get) => void get(baseAtom)) as AtomWithEffect + const effectAtom = atom((get) => void get(baseAtom)) as Atom & { + effect: Effect + } effectAtom.effect = effect return effectAtom function refresh(ref: Ref) { diff --git a/src/index.ts b/src/index.ts index 7d7c89b..03f951d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,2 +1,3 @@ export { atomEffect } from './atomEffect' export { withAtomEffect } from './withAtomEffect' +export { observe } from './observe' diff --git a/src/withAtomEffect.ts b/src/withAtomEffect.ts index 2792e7a..cf4bd8e 100644 --- a/src/withAtomEffect.ts +++ b/src/withAtomEffect.ts @@ -1,11 +1,11 @@ import type { Atom } from 'jotai/vanilla' -import type { AtomWithEffect, Effect } from './atomEffect' +import type { Effect } from './atomEffect' import { atomEffect } from './atomEffect' export function withAtomEffect>( targetAtom: T, effect: Effect -): AtomWithEffect { +): T & { effect: Effect } { const effectAtom = atomEffect((get, set) => { const getter = ((a) => a === targetWithEffect ? get(targetAtom) : get(a)) as typeof get @@ -19,7 +19,7 @@ export function withAtomEffect>( effectAtom.debugPrivate = true } const descriptors = Object.getOwnPropertyDescriptors( - targetAtom as AtomWithEffect + targetAtom as T & { effect: Effect } ) descriptors.read.value = (get) => { try {