UNPKG

2.61 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var react = require('react');
6var jotai = require('jotai');
7
8var useUpdateAtom = function useUpdateAtom(anAtom) {
9 var writeOnlyAtom = react.useMemo(function () {
10 return jotai.atom(null, function (_get, set, update) {
11 return set(anAtom, update);
12 });
13 }, [anAtom]);
14 return jotai.useAtom(writeOnlyAtom)[1];
15}; // -----------------------------------------------------------------------
16
17var RESET = Symbol();
18var atomWithReset = function atomWithReset(initialValue) {
19 var anAtom = jotai.atom(initialValue, function (get, set, update) {
20 if (update === RESET) {
21 set(anAtom, initialValue);
22 } else {
23 set(anAtom, typeof update === 'function' ? update(get(anAtom)) : update);
24 }
25 });
26 return anAtom;
27};
28var useResetAtom = function useResetAtom(anAtom) {
29 var writeOnlyAtom = react.useMemo(function () {
30 return jotai.atom(null, function (_get, set, _update) {
31 return set(anAtom, RESET);
32 });
33 }, [anAtom]);
34 return jotai.useAtom(writeOnlyAtom)[1];
35};
36function useReducerAtom(anAtom, reducer) {
37 var _useAtom = jotai.useAtom(anAtom),
38 state = _useAtom[0],
39 setState = _useAtom[1];
40
41 var dispatch = react.useCallback(function (action) {
42 setState(function (prev) {
43 return reducer(prev, action);
44 });
45 }, [setState, reducer]);
46 return [state, dispatch];
47}
48function atomWithReducer(initialValue, reducer) {
49 var anAtom = jotai.atom(initialValue, function (get, set, action) {
50 return set(anAtom, reducer(get(anAtom), action));
51 });
52 return anAtom;
53}
54function atomFamily(initializeRead, initializeWrite, areEqual) {
55 if (areEqual === void 0) {
56 areEqual = Object.is;
57 }
58
59 var atoms = [];
60
61 var createAtom = function createAtom(param) {
62 var found = atoms.find(function (x) {
63 return areEqual(x[0], param);
64 });
65
66 if (found) {
67 return found[1];
68 }
69
70 var newAtom = jotai.atom(initializeRead(param), initializeWrite && initializeWrite(param));
71 atoms.unshift([param, newAtom]);
72 return newAtom;
73 };
74
75 createAtom.remove = function (p) {
76 var index = atoms.findIndex(function (x) {
77 return x[0] === p;
78 });
79
80 if (index >= 0) {
81 atoms.splice(index, 1);
82 }
83 };
84
85 return createAtom;
86} // -----------------------------------------------------------------------
87
88exports.atomFamily = atomFamily;
89exports.atomWithReducer = atomWithReducer;
90exports.atomWithReset = atomWithReset;
91exports.useReducerAtom = useReducerAtom;
92exports.useResetAtom = useResetAtom;
93exports.useUpdateAtom = useUpdateAtom;