UNPKG

1.25 kBJavaScriptView Raw
1import { useMemo, useCallback } from 'react';
2import { atom, useAtom } from 'jotai';
3
4const useUpdateAtom = anAtom => {
5 const writeOnlyAtom = useMemo(() => atom(null, (_get, set, update) => set(anAtom, update)), [anAtom]);
6 return useAtom(writeOnlyAtom)[1];
7};
8const RESET = Symbol();
9const atomWithReset = initialValue => {
10 const anAtom = atom(initialValue, (get, set, update) => {
11 if (update === RESET) {
12 set(anAtom, initialValue);
13 } else {
14 set(anAtom, typeof update === 'function' ? update(get(anAtom)) : update);
15 }
16 });
17 return anAtom;
18};
19const useResetAtom = anAtom => {
20 const writeOnlyAtom = useMemo(() => atom(null, (_get, set, _update) => set(anAtom, RESET)), [anAtom]);
21 return useAtom(writeOnlyAtom)[1];
22};
23const useReducerAtom = (anAtom, reducer) => {
24 const [state, setState] = useAtom(anAtom);
25 const dispatch = useCallback(action => {
26 setState(prev => reducer(prev, action));
27 }, [setState, reducer]);
28 return [state, dispatch];
29};
30const atomWithReducer = (initialValue, reducer) => {
31 const anAtom = atom(initialValue, (get, set, action) => set(anAtom, reducer(get(anAtom), action)));
32 return anAtom;
33};
34
35export { atomWithReducer, atomWithReset, useReducerAtom, useResetAtom, useUpdateAtom };