-
-
Notifications
You must be signed in to change notification settings - Fork 642
/
Copy pathuseAtomValue.ts
164 lines (149 loc) · 4.46 KB
/
useAtomValue.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/// <reference types="react/experimental" />
import ReactExports, { useDebugValue, useEffect, useReducer } from 'react'
import type { Atom, ExtractAtomValue } from '../vanilla.ts'
import { useStore } from './Provider.ts'
type Store = ReturnType<typeof useStore>
const isPromiseLike = (x: unknown): x is PromiseLike<unknown> =>
typeof (x as any)?.then === 'function'
const attachPromiseMeta = <T>(
promise: PromiseLike<T> & {
status?: 'pending' | 'fulfilled' | 'rejected'
value?: T
reason?: unknown
},
) => {
promise.status = 'pending'
promise.then(
(v) => {
promise.status = 'fulfilled'
promise.value = v
},
(e) => {
promise.status = 'rejected'
promise.reason = e
},
)
}
const use =
ReactExports.use ||
(<T>(
promise: PromiseLike<T> & {
status?: 'pending' | 'fulfilled' | 'rejected'
value?: T
reason?: unknown
},
): T => {
if (promise.status === 'pending') {
throw promise
} else if (promise.status === 'fulfilled') {
return promise.value as T
} else if (promise.status === 'rejected') {
throw promise.reason
} else {
attachPromiseMeta(promise)
throw promise
}
})
const continuablePromiseMap = new WeakMap<
PromiseLike<unknown>,
Promise<unknown>
>()
const createContinuablePromise = <T>(promise: PromiseLike<T>) => {
let continuablePromise = continuablePromiseMap.get(promise)
if (!continuablePromise) {
continuablePromise = new Promise<T>((resolve, reject) => {
let curr = promise
const onFulfilled = (me: PromiseLike<T>) => (v: T) => {
if (curr === me) {
resolve(v)
}
}
const onRejected = (me: PromiseLike<T>) => (e: unknown) => {
if (curr === me) {
reject(e)
}
}
const registerCancelHandler = (p: PromiseLike<T>) => {
if ('onCancel' in p && typeof p.onCancel === 'function') {
p.onCancel((nextValue: PromiseLike<T> | T) => {
if (import.meta.env?.MODE !== 'production' && nextValue === p) {
throw new Error('[Bug] p is not updated even after cancelation')
}
if (isPromiseLike(nextValue)) {
continuablePromiseMap.set(nextValue, continuablePromise!)
curr = nextValue
nextValue.then(onFulfilled(nextValue), onRejected(nextValue))
registerCancelHandler(nextValue)
} else {
resolve(nextValue)
}
})
}
}
promise.then(onFulfilled(promise), onRejected(promise))
registerCancelHandler(promise)
})
continuablePromiseMap.set(promise, continuablePromise)
}
return continuablePromise
}
type Options = Parameters<typeof useStore>[0] & {
delay?: number
}
export function useAtomValue<Value>(
atom: Atom<Value>,
options?: Options,
): Awaited<Value>
export function useAtomValue<AtomType extends Atom<unknown>>(
atom: AtomType,
options?: Options,
): Awaited<ExtractAtomValue<AtomType>>
export function useAtomValue<Value>(atom: Atom<Value>, options?: Options) {
const store = useStore(options)
const [[valueFromReducer, storeFromReducer, atomFromReducer], rerender] =
useReducer<readonly [Value, Store, typeof atom], undefined, []>(
(prev) => {
const nextValue = store.get(atom)
if (
Object.is(prev[0], nextValue) &&
prev[1] === store &&
prev[2] === atom
) {
return prev
}
return [nextValue, store, atom]
},
undefined,
() => [store.get(atom), store, atom],
)
let value = valueFromReducer
if (storeFromReducer !== store || atomFromReducer !== atom) {
rerender()
value = store.get(atom)
}
const delay = options?.delay
useEffect(() => {
const unsub = store.sub(atom, () => {
if (typeof delay === 'number') {
const value = store.get(atom)
if (isPromiseLike(value)) {
attachPromiseMeta(createContinuablePromise(value))
}
// delay rerendering to wait a promise possibly to resolve
setTimeout(rerender, delay)
return
}
rerender()
})
rerender()
return unsub
}, [store, atom, delay])
useDebugValue(value)
// The use of isPromiseLike is to be consistent with `use` type.
// `instanceof Promise` actually works fine in this case.
if (isPromiseLike(value)) {
const promise = createContinuablePromise(value)
return use(promise)
}
return value as Awaited<Value>
}