selectorFamily

Signature
selectorFamily<K, T>(factory: (key: K) => (get: GetFn) => T): SelectorFamily<K, T>

valdres Create a keyed collection of derived selectors

Creates a family of selectors keyed by a parameter. Each selector derives its value from atoms or other selectors based on the key.

Usage

import { selectorFamily } from "valdres"
import { userAtom } from "./userAtom"

const userDisplayNameSelector = selectorFamily(id => get => {
    const { firstName, lastName } = get(userAtom(id))
    return `${firstName} ${lastName}`
})

store.get(userDisplayNameSelector("user-1")) // "John Doe"

With async computation

const userPostsSelector = selectorFamily(userId => async get => {
    const res = await fetch(`/api/users/${userId}/posts`)
    return res.json()
})

In React

import { useValue } from "valdres-react"

function UserName({ userId }) {
    const displayName = useValue(userDisplayNameSelector(userId))
    return <span>{displayName}</span>
}

See also