From 6c9e030c7b3c07ae8831f43364f5fd61035f158e Mon Sep 17 00:00:00 2001 From: Daishi Kato Date: Mon, 23 Oct 2023 21:55:09 +0900 Subject: [PATCH] feat(vanilla): prefer using `this` for atom config (#2186) --- src/vanilla/atom.ts | 20 ++++++++++++++------ src/vanilla/utils/freezeAtom.ts | 4 +++- src/vanilla/utils/unwrap.ts | 3 ++- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/src/vanilla/atom.ts b/src/vanilla/atom.ts index f79830139a..d7fba78de9 100644 --- a/src/vanilla/atom.ts +++ b/src/vanilla/atom.ts @@ -92,14 +92,22 @@ export function atom( config.read = read as Read> } else { config.init = read - config.read = (get) => get(config) - config.write = ((get: Getter, set: Setter, arg: SetStateAction) => - set( - config as unknown as PrimitiveAtom, + config.read = function (get) { + return get(this) + } + config.write = function ( + this: PrimitiveAtom, + get: Getter, + set: Setter, + arg: SetStateAction + ) { + return set( + this, typeof arg === 'function' - ? (arg as (prev: Value) => Value)(get(config)) + ? (arg as (prev: Value) => Value)(get(this)) : arg - )) as unknown as Write + ) + } as unknown as Write } if (write) { config.write = write diff --git a/src/vanilla/utils/freezeAtom.ts b/src/vanilla/utils/freezeAtom.ts index b3f3f8977a..004c1eb009 100644 --- a/src/vanilla/utils/freezeAtom.ts +++ b/src/vanilla/utils/freezeAtom.ts @@ -34,7 +34,9 @@ export function freezeAtomCreator< return ((...params: any[]) => { const anAtom = createAtom(...params) const origRead = anAtom.read - anAtom.read = (get, options) => deepFreeze(origRead(get, options)) + anAtom.read = function (get, options) { + return deepFreeze(origRead.call(this, get, options)) + } return anAtom }) as CreateAtom } diff --git a/src/vanilla/utils/unwrap.ts b/src/vanilla/utils/unwrap.ts index 1b766f381b..a816161114 100644 --- a/src/vanilla/utils/unwrap.ts +++ b/src/vanilla/utils/unwrap.ts @@ -100,7 +100,8 @@ export function unwrap( } return state.f }, - (anAtom as WritableAtom).write + (_get, set, ...args) => + set(anAtom as WritableAtom, ...args) ) }, anAtom,