Document the use of a function as the second parameter of set
#2268
-
SummaryWhile exploring the atom page, I discovered that it's possible to pass a function as the second parameter of const countAtom = atom(1)
const derivedAtom = atom(
(get) => get(countAtom),
(get, set, action) => {
set(countAtom, (c) => c + 1)
},
) It would be better if we document the behavior explicitly in the "derived atoms" section of the page. https://github.com/pmndrs/jotai/blob/234dff9/docs/core/atom.mdx#L26-L50 const writeOnlyAtom = atom(
null, // it's a convention to pass `null` for the first argument
(get, set, update) => {
// `update` is any single value we receive for updating this atom
set(priceAtom, get(priceAtom) - update.discount)
+ // We can also pass a function as the second parameter
+ // The function will be invoked, receiving the atom's current value as its first parameter
+ set(priceAtom, (price) => price - update.discount)
},
) Link to reproduction |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 2 replies
-
I can open a PR if you like the idea. |
Beta Was this translation helpful? Give feedback.
-
Internally, it will simply invoke the target atom's write function. So, it is possible because countAtom accepts such a function.
Yes, feel free to open a PR please. |
Beta Was this translation helpful? Give feedback.
-
I wonder if it would be possible to type const handlerAtom = atom<(() => void) | null>(null);
// ...
// sets anAtom to undefined
set(handlerAtom, () => { /* do stuff */ }); Something like this might avoid many erroneous cases: type SetStateAction<Value> = Value extends ((...args: never[]) => unknown)
? (prev: Value) => Value
: Value | ((prev: Value) => Value); (That exact code breaks with some wide value types, though, so I'm not exactly sure how it would be implemented.) |
Beta Was this translation helpful? Give feedback.
#2271