Skip to content

Commit

Permalink
feat(vanilla): prefer using this for atom config (#2186)
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi authored Oct 23, 2023
1 parent cdbfcdf commit 6c9e030
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 8 deletions.
20 changes: 14 additions & 6 deletions src/vanilla/atom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,22 @@ export function atom<Value, Args extends unknown[], Result>(
config.read = read as Read<Value, SetAtom<Args, Result>>
} else {
config.init = read
config.read = (get) => get(config)
config.write = ((get: Getter, set: Setter, arg: SetStateAction<Value>) =>
set(
config as unknown as PrimitiveAtom<Value>,
config.read = function (get) {
return get(this)
}
config.write = function (
this: PrimitiveAtom<Value>,
get: Getter,
set: Setter,
arg: SetStateAction<Value>
) {
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<Args, Result>
)
} as unknown as Write<Args, Result>
}
if (write) {
config.write = write
Expand Down
4 changes: 3 additions & 1 deletion src/vanilla/utils/freezeAtom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
3 changes: 2 additions & 1 deletion src/vanilla/utils/unwrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ export function unwrap<Value, Args extends unknown[], Result, PendingValue>(
}
return state.f
},
(anAtom as WritableAtom<Value, unknown[], unknown>).write
(_get, set, ...args) =>
set(anAtom as WritableAtom<Value, unknown[], unknown>, ...args)
)
},
anAtom,
Expand Down

1 comment on commit 6c9e030

@vercel
Copy link

@vercel vercel bot commented on 6c9e030 Oct 23, 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.