1 | import { useMemo, useCallback } from 'react';
|
2 | import { atom, useAtom } from 'jotai';
|
3 |
|
4 | const useUpdateAtom = anAtom => {
|
5 | const writeOnlyAtom = useMemo(() => atom(null, (_get, set, update) => set(anAtom, update)), [anAtom]);
|
6 | return useAtom(writeOnlyAtom)[1];
|
7 | };
|
8 | const RESET = Symbol();
|
9 | const 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 | };
|
19 | const useResetAtom = anAtom => {
|
20 | const writeOnlyAtom = useMemo(() => atom(null, (_get, set, _update) => set(anAtom, RESET)), [anAtom]);
|
21 | return useAtom(writeOnlyAtom)[1];
|
22 | };
|
23 | const 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 | };
|
30 | const atomWithReducer = (initialValue, reducer) => {
|
31 | const anAtom = atom(initialValue, (get, set, action) => set(anAtom, reducer(get(anAtom), action)));
|
32 | return anAtom;
|
33 | };
|
34 |
|
35 | export { atomWithReducer, atomWithReset, useReducerAtom, useResetAtom, useUpdateAtom };
|