Skip to main content

injectSelf

import { injectSelf } from '@zedux/react'

An unrestricted injector that returns the currently-evaluating atom instance. This atom instance is not fully initialized on initial evaluation. We call this not-fully-initialized instance a PartialAtomInstance.

PartialAtomInstance

On initial evaluation, injectSelf() returns a "PartialAtomInstance", which is an AtomInstance without exports, promise, or store properties set. Those aren't set until the initial evaluation finishes.

This PartialAtomInstance does have all other AtomInstance properties and methods.

When initial evaluation ends, the PartialAtomInstance is given its exports, promise, and store fields via mutation. This means that when used asynchronously e.g. in callbacks or effects, the instance will have those fields:

const exampleAtom = atom('example', () => {
const instance = injectSelf()

instance.store // doesn't exist

injectEffect(() => {
instance.store // exists!
}, [])

return api().setExports({
myExport: () => instance.store, // exists!
})
})

Examples

Seeing the fully-qualified id of the current atom instance:

Live Sandbox
1234567891011
const exampleAtom = atom('example', (param1: string, param2: number) => {
const { id } = injectSelf()

return id
})

function Id() {
const value = useAtomValue(exampleAtom, ['a', 1])

return <pre>{value}</pre>
}

Accessing the store without using injectStore():

const counterAtom = atom('counter', () => {
const instance = injectSelf()

const increment = () =>
(instance as AtomInstanceType<typeof counterAtom>).store.setState(
state => state + 1
)

return api(1).setExports({ increment })
})

Signature

injectSelf = () => maybePartialAtomInstance
Returns

A "PartialAtomInstance" on initial evaluation. This PartialAtomInstance _is_ the currently-evaluating AtomInstance but without some properties that AtomInstances always have - exports, promise, and store.

On subsequent evaluations, injectSelf() returns the full AtomInstance object.

See Also