Document the use of a function as the second parameter of `set`
mon-jai opened this issue · comments
Summary
While exploring the atom page, I discovered that it's possible to pass a function as the second parameter of set
. This function will be automatically invoked, receiving the atom's current value as its first parameter.
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
I can open a PR if you like the idea.
I discovered that it's possible to pass a function as the second parameter of set.
Internally, it will simply invoke the target atom's write function. So, it is possible because countAtom accepts such a function.
I can open a PR if you like the idea.
Yes, feel free to open a PR please.