Skip to main content

injectAtomGetters

import { injectAtomGetters } from '@zedux/react'

An unrestricted injector that returns an AtomGetters object

Examples

Live Sandbox
123456789101112131415161718192021222324
const secondsAtom = atom('seconds', (startingNumber: number) => {
const store = injectStore(startingNumber)

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

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

return store
})

const sumAtom = atom('sum', (...nums: number[]) => {
const { get } = injectAtomGetters()

// loops are fine!
return nums.reduce((sum, num) => sum + get(secondsAtom, [num]), 0)
})

function Seconds() {
const sum = useAtomValue(sumAtom, [1, 10, 100])

return <div>Sum of 3 counters: {sum}</div>
}
Live Sandbox
123456789101112131415161718192021222324252627282930313233
const secondsAtom = atom('seconds', () => {
const store = injectStore(0)

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

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

return store
})

const lazyAtom = ion('lazy', ({ get }) => {
const { ecosystem } = injectAtomGetters()

// ion's get function would register a dynamic graph dependency here.
// Try removing the "ecosystem.":
const seconds = ecosystem.get(secondsAtom)

return seconds
})

function Seconds() {
const lazySeconds = useAtomValue(lazyAtom)
const instance = useAtomInstance(lazyAtom)

return (
<>
<div>Unchanging Seconds: {lazySeconds}</div>
<button onClick={() => instance.invalidate()}>Force Update</button>
</>
)
}

Miscellaneous:

const { ecosystem, get, getInstance, select } = injectAtomGetters()

const dynamicVal = get(myAtom)
const staticVal = ecosystem.get(myAtom)
const instance = getInstance(myAtom)
const selectedVal = select(myAtomSelector)

const withParams = get(myAtom, ['param 1', 'param 2'])
const instanceWithParams = getInstance(myAtom, ['param 1', 'param 2'])

// AtomGetters can be used in loops:
for (const id of ids) {
const val = get(myAtom, [id])
}

// .. any kind of loop
ids.map(id => get(myAtom, [id]))

// in control flow statements
const val = useAtomA ? get(atomA) : get(atomB)

// asynchronously:
injectEffect(() => {
const currentVal = get(myAtom)
}, []) // don't have to pass `get`

// passing an instance to get (also registers a dynamic dependency when called
// during atom evaluation):
const fromInstance = get(instance)

Signature

injectAtomGetters = () => atomGetters
Returns

An AtomGetters object:

const { ecosystem, get, getInstance, select } = injectAtomGetters()

See Also