Extend atom onMount with getter #2236
-
Hi, I was wondering if it would be possible to extend the onMount function with a getter? Currently it is only possible to set a value in there, but it would help improve our code base in some instances. E.g. currently we registered atom effects for several atoms, in order to do so we need to mount the effect in component.
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
It's our design choice to only support const countAtom = atom(1)
const anotherCountAtom = atom(2)
const initAtom = atom(null, (get, set) => {
set(anotherCountAtom, get(countAtom) * 10)
})
initAtom.onMount = (init) => {
init()
} |
Beta Was this translation helpful? Give feedback.
-
Awesome, thanks! |
Beta Was this translation helpful? Give feedback.
-
I'm late to the party but the way to do this is with atom composition. import { atomEffect } from 'jotai-effect'
const myValueBaseAtom = atom(0)
const myValueAtomEffect = atomEffect((get, set) => {
const myValue= get(myValueBaseAtom)
})
const myValueAtom = atom(
(get) => {
get(myValueAtomEffect)
return get(myValueBaseAtom)
},
(_get, set, value: number) => set(myValueBaseAtom, value)
) Alternatively, you can just use withAtomEffect, which is equivalent to above. import { withAtomEffect } from 'jotai-effect'
const myValueAtom = withAtomEffect(atom(0), (get, set) => {
const myValue= get(myValueAtom)
}) |
Beta Was this translation helpful? Give feedback.
It's our design choice to only support
set
in onMount. You should create a new atom. We prefer atom composition.