Created
January 6, 2022 08:15
-
-
Save jtmthf/b1f2fd76ebf56e6ff373bc0c0a4f68c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Atom } from 'jotai'; | |
import { selectAtom, useAtomValue} from 'jotai/utils'; | |
import { useMemo } from 'react'; | |
import { createTrackedSelector } from 'react-tracked'; | |
type ResolveType<T> = T extends Promise<infer V> ? V : T | |
export function useSelectAtom<Value, Slice>( | |
atom: Atom<Value>, | |
selector: (v: ResolveType<Value>) => Slice, | |
equalityFn: (a: Slice, b: Slice) => boolean = Object.is | |
): ResolveType<Slice> { | |
const selectedAtom = useMemo(() => selectAtom(atom, selector, equalityFn), [atom, selector, equalityFn]); | |
return useAtomValue(selectedAtom) | |
} | |
export function createAtomSelector<Value>(atom: Atom<Value>): <Slice>(selector: (value: Value) => Slice) => Slice { | |
return <Slice>(selector: (v: ResolveType<Value>) => Slice) => { | |
return useSelectAtom(atom, selector); | |
} | |
} | |
export function createTrackedAtom<Value>(atom: Atom<Value>) { | |
return createTrackedSelector(createAtomSelector(atom)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment