UNPKG

1.97 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}; // -----------------------------------------------------------------------
8
9const RESET = Symbol();
10const atomWithReset = initialValue => {
11 const anAtom = atom(initialValue, (get, set, update) => {
12 if (update === RESET) {
13 set(anAtom, initialValue);
14 } else {
15 set(anAtom, typeof update === 'function' ? update(get(anAtom)) : update);
16 }
17 });
18 return anAtom;
19};
20const useResetAtom = anAtom => {
21 const writeOnlyAtom = useMemo(() => atom(null, (_get, set, _update) => set(anAtom, RESET)), [anAtom]);
22 return useAtom(writeOnlyAtom)[1];
23};
24function useReducerAtom(anAtom, reducer) {
25 const [state, setState] = useAtom(anAtom);
26 const dispatch = useCallback(action => {
27 setState(prev => reducer(prev, action));
28 }, [setState, reducer]);
29 return [state, dispatch];
30}
31function atomWithReducer(initialValue, reducer) {
32 const anAtom = atom(initialValue, (get, set, action) => set(anAtom, reducer(get(anAtom), action)));
33 return anAtom;
34}
35function atomFamily(initializeRead, initializeWrite, areEqual = Object.is) {
36 const atoms = [];
37
38 const createAtom = param => {
39 const found = atoms.find(x => areEqual(x[0], param));
40
41 if (found) {
42 return found[1];
43 }
44
45 const newAtom = atom(initializeRead(param), initializeWrite && initializeWrite(param));
46 atoms.unshift([param, newAtom]);
47 return newAtom;
48 };
49
50 createAtom.remove = p => {
51 const index = atoms.findIndex(x => x[0] === p);
52
53 if (index >= 0) {
54 atoms.splice(index, 1);
55 }
56 };
57
58 return createAtom;
59} // -----------------------------------------------------------------------
60
61export { atomFamily, atomWithReducer, atomWithReset, useReducerAtom, useResetAtom, useUpdateAtom };