-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathRecoilNexus.tsx
59 lines (44 loc) · 1.8 KB
/
RecoilNexus.tsx
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
50
51
52
53
54
55
56
57
58
59
import { useGetRecoilValueInfo_UNSTABLE } from 'recoil';
import { RecoilState, RecoilValue, useRecoilCallback, useRecoilTransaction_UNSTABLE } from 'recoil';
interface Nexus {
get?: <T>(atom: RecoilValue<T>) => T
getPromise?: <T>(atom: RecoilValue<T>) => Promise<T>
set?: <T>(atom: RecoilState<T>, valOrUpdater: T | ((currVal: T) => T)) => void
reset?: (atom: RecoilState<any>) => void
}
const nexus: Nexus = {}
export default function RecoilNexus() {
nexus.get = useRecoilCallback<[atom: RecoilValue<any>], any>(({ snapshot }) =>
function <T>(atom: RecoilValue<T>) {
return snapshot.getLoadable(atom).contents
}, [])
nexus.getPromise = useRecoilCallback<[atom: RecoilValue<any>], Promise<any>>(({ snapshot }) =>
function <T>(atom: RecoilValue<T>) {
return snapshot.getPromise(atom)
}, [])
const getInfo = useGetRecoilValueInfo_UNSTABLE()
const transact = useRecoilTransaction_UNSTABLE(({ set }) => set)
nexus.set = useRecoilCallback(({ set }) => {
return function <T>(recoilState: RecoilState<T>, valOrUpdater: T | ((currVal: T) => T)) {
const update = {
"atom": transact,
"selector": set
}[getInfo(recoilState).type]
update(recoilState, valOrUpdater)
}
}, [])
nexus.reset = useRecoilCallback(({ reset }) => reset, [])
return null
}
export function getRecoil<T>(atom: RecoilValue<T>): T {
return nexus.get!(atom)
}
export function getRecoilPromise<T>(atom: RecoilValue<T>): Promise<T> {
return nexus.getPromise!(atom)
}
export function setRecoil<T>(atom: RecoilState<T>, valOrUpdater: T | ((currVal: T) => T)) {
nexus.set!(atom, valOrUpdater)
}
export function resetRecoil(atom: RecoilState<any>) {
nexus.reset!(atom)
}