UNPKG

jotai

Version:

👻 Next gen state management that will spook you

33 lines (27 loc) • 871 B
import { atom } from 'jotai'; import { optic, modify, set, collect, preview, get } from 'optics-ts'; function focusAtom(baseAtom, callback) { const focus = callback(optic()); const derivedAtom = atom(get => { const newValue = getValueUsingOptic(focus, get(baseAtom)); return newValue; }, (_, set$1, update) => { const newValueProducer = update instanceof Function ? modify(focus)(update) : set(focus)(update); set$1(baseAtom, newValueProducer); }); derivedAtom.scope = baseAtom.scope; return derivedAtom; } const getValueUsingOptic = (focus, bigValue) => { if (focus._tag === 'Traversal') { const values = collect(focus)(bigValue); return values; } if (focus._tag === 'Prism') { const value = preview(focus)(bigValue); return value; } const value = get(focus)(bigValue); return value; }; export { focusAtom };