-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
49 lines (40 loc) · 1.16 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import {
atom,
useAtom as jotaiUseAtom,
useAtomValue as jotaiUseAtomValue,
useSetAtom as jotaiUseSetAtom,
} from "jotai";
const fallbackAtom = atom();
export default function getAPIFromAtoms(atoms) {
const atomsEntries = Object.entries(atoms);
function useJotai(atomInput, jotaiHook) {
if (typeof atomInput === "string") {
const atomEntry = atomsEntries.find(([key]) => key === atomInput);
if (atomEntry) {
return jotaiHook(atomEntry[1]);
}
return jotaiHook(fallbackAtom);
}
return jotaiHook(atomInput ?? fallbackAtom);
}
function useAtom(atom) {
return useJotai(atom, jotaiUseAtom);
}
function useAtomValue(atom) {
return useJotai(atom, jotaiUseAtomValue);
}
function useSetAtom(atom) {
return useJotai(atom, jotaiUseSetAtom);
}
function getAtom(atomName) {
const atomEntry = atomsEntries.find(([key]) => key === atomName);
if (atomEntry) {
return atomEntry[1];
}
return fallbackAtom;
}
const selectAtom = (atomName, selector) => {
return atom((get) => selector(get(getAtom(atomName))));
};
return { useAtom, useAtomValue, useSetAtom, getAtom, selectAtom };
}