Skip to main content

injectAtomValue

import { injectAtomValue } from '@zedux/react'

An injector that accepts an atom template and its params and registers a dynamic graph dependency on the resolved atom instance. Returns the current value of the injected atom instance's store.

The atom instance that uses this injector will reevaluate every time the resolved atom instance's state changes.

This injector is essentially an alias for:

const { get } = injectAtomGetters()
const value = get(otherAtom)

Except more restrictive since this is a normal injector while injectAtomGetters() is unrestricted and get is not an injector at all.

Example

Live Sandbox
1234567891011121314151617181920212223
const secondsAtom = atom('seconds', () => {
const store = injectStore(0)

injectEffect(() => {
const intervalId = setInterval(() => store.setState(val => val + 1), 1000)

return () => clearInterval(intervalId)
}, [])

return store
})

const timesFiveAtom = atom('timesFive', () => {
const seconds = injectAtomValue(secondsAtom)

return seconds * 5
})

function Seconds() {
const state = useAtomValue(timesFiveAtom)

return <div>Seconds Times Five: {state}</div>
}

Miscellaneous:

const currentState = injectAtomValue(myAtom)

const passingParams = injectAtomValue(myAtom, ['param 1', 'param 2'])

// passing an atom instance registers a dynamic dependency on that instance
const passingAnInstance = injectAtomValue(instance)

Signature

injectAtomValue = (atom, params?) => state
atom

Required. An atom template or atom instance.

If an atom template is passed, you must also pass any required params of the atom.

If an atom instance is passed, the params are ignored. In this case, injectAtomValue() returns the current value of the passed instance (essentially instance.getState()).

In all cases, injectAtomValue() adds a dynamic dependency on the resolved atom instance.

params

Required if the passed atom template takes required params. Optional if not.

Don't pass this or pass an empty array if the atom does not take params or if passing an atom instance.

Returns

The current value of the resolved atom instance's store.

Uses the passed atom template + params combo to find an existing atom instance. If no instance is found, injectAtomValue() creates one using the template and params and returns its initial value.

See Also