Is it feasible to pass the store into onMount as the second argument?
#3175
Unanswered
alecmce-maltedai
asked this question in
Ideas
Replies: 1 comment 1 reply
-
|
onInit can do this, but the api is a little advanced. import {
INTERNAL_getBuildingBlocksRev2,
INTERNAL_initializeStoreHooksRev2,
} from 'jotai/vanilla/internals'
import { atom } from 'jotai'
const anAtom = atom(0)
// onInit fires once per store when the atomState is being defined
// the store is passed in as the only argument
anAtom.unstable_onInit = (store) => {
// buildingBlocks are all the internals that make up Jotai
const buildingBlocks = INTERNAL_getBuildingBlocksRev2(store)
// store hooks in buildingBlocks[6] are for atom events
// they need to be initialized to work
// store hooks events
// m: mount
// u: unmount
// c: change - value changed
// f: flush - notify all subscribers of changes
const storeHooks = INTERNAL_initializeStoreHooksRev2(buildingBlocks[6])
// storeHooks.m.add(undefined, () => {...}) - fires when any atom mounts
// storeHooks.m.add(anAtom, () => {...}) - fires when anAtom mounts
storeHooks.m.add(anAtom, () => {
// synchronous on mount timing
// store is available here.
})
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
There are a few situations like animations where I want to break-out of the Jotai way and create an atom that has more complex functionality structured by an
onMountwith various subscriptions that writes back to itself. Primarily I use this for animation state machines.To do that, I need to access the store, so the first line of
onMountisconst store = getDefaultStore(). This feels very brittle. It would be useful if the store could be exposed to theonMountfunction so this sort of implementation is easier to achieve.Is there any reason not to do this?
Thanks for the library.
Beta Was this translation helpful? Give feedback.
All reactions