1 | import { useCallback, useContext, useEffect, useLayoutEffect, useState, useRef, useMemo } from 'react';
|
2 | import defaultConfig, { CACHE_REVALIDATORS, CONCURRENT_PROMISES, CONCURRENT_PROMISES_TS, FOCUS_REVALIDATORS, MUTATION_TS, cache } from './config';
|
3 | import isDocumentVisible from './libs/is-document-visible';
|
4 | import isOnline from './libs/is-online';
|
5 | import throttle from './libs/throttle';
|
6 | import SWRConfigContext from './swr-config-context';
|
7 | const IS_SERVER = typeof window === 'undefined';
|
8 |
|
9 |
|
10 |
|
11 | const useIsomorphicLayoutEffect = IS_SERVER ? useEffect : useLayoutEffect;
|
12 | const trigger = (_key, shouldRevalidate = true) => {
|
13 |
|
14 |
|
15 | const [key, , keyErr] = cache.serializeKey(_key);
|
16 | if (!key)
|
17 | return;
|
18 | const updaters = CACHE_REVALIDATORS[key];
|
19 | if (key && updaters) {
|
20 | const currentData = cache.get(key);
|
21 | const currentError = cache.get(keyErr);
|
22 | for (let i = 0; i < updaters.length; ++i) {
|
23 | updaters[i](shouldRevalidate, currentData, currentError, i > 0);
|
24 | }
|
25 | }
|
26 | };
|
27 | const broadcastState = (key, data, error) => {
|
28 | const updaters = CACHE_REVALIDATORS[key];
|
29 | if (key && updaters) {
|
30 | for (let i = 0; i < updaters.length; ++i) {
|
31 | updaters[i](false, data, error);
|
32 | }
|
33 | }
|
34 | };
|
35 | const mutate = async (_key, _data, shouldRevalidate = true) => {
|
36 | const [key] = cache.serializeKey(_key);
|
37 | if (!key)
|
38 | return;
|
39 |
|
40 | if (typeof _data === 'undefined')
|
41 | return trigger(_key, shouldRevalidate);
|
42 |
|
43 | MUTATION_TS[key] = Date.now() - 1;
|
44 | let data, error;
|
45 | if (_data && typeof _data === 'function') {
|
46 |
|
47 | try {
|
48 | data = await _data(cache.get(key));
|
49 | }
|
50 | catch (err) {
|
51 | error = err;
|
52 | }
|
53 | }
|
54 | else if (_data && typeof _data.then === 'function') {
|
55 |
|
56 | try {
|
57 | data = await _data;
|
58 | }
|
59 | catch (err) {
|
60 | error = err;
|
61 | }
|
62 | }
|
63 | else {
|
64 | data = _data;
|
65 | }
|
66 | if (typeof data !== 'undefined') {
|
67 |
|
68 | cache.set(key, data, false);
|
69 | }
|
70 |
|
71 | const updaters = CACHE_REVALIDATORS[key];
|
72 | if (updaters) {
|
73 | for (let i = 0; i < updaters.length; ++i) {
|
74 | updaters[i](!!shouldRevalidate, data, error, i > 0);
|
75 | }
|
76 | }
|
77 |
|
78 | if (error)
|
79 | throw error;
|
80 | return data;
|
81 | };
|
82 | function useSWR(...args) {
|
83 | let _key, fn, config = {};
|
84 | if (args.length >= 1) {
|
85 | _key = args[0];
|
86 | }
|
87 | if (args.length > 2) {
|
88 | fn = args[1];
|
89 | config = args[2];
|
90 | }
|
91 | else {
|
92 | if (typeof args[1] === 'function') {
|
93 | fn = args[1];
|
94 | }
|
95 | else if (typeof args[1] === 'object') {
|
96 | config = args[1];
|
97 | }
|
98 | }
|
99 |
|
100 |
|
101 |
|
102 |
|
103 | const [key, fnArgs, keyErr] = cache.serializeKey(_key);
|
104 | config = Object.assign({}, defaultConfig, useContext(SWRConfigContext), config);
|
105 | if (typeof fn === 'undefined') {
|
106 |
|
107 | fn = config.fetcher;
|
108 | }
|
109 | const initialData = cache.get(key) || config.initialData;
|
110 | const initialError = cache.get(keyErr);
|
111 |
|
112 |
|
113 |
|
114 | const stateDependencies = useRef({
|
115 | data: false,
|
116 | error: false,
|
117 | isValidating: false
|
118 | });
|
119 | const stateRef = useRef({
|
120 | data: initialData,
|
121 | error: initialError,
|
122 | isValidating: false
|
123 | });
|
124 | const rerender = useState(null)[1];
|
125 | let dispatch = useCallback(payload => {
|
126 | let shouldUpdateState = false;
|
127 | for (let k in payload) {
|
128 | stateRef.current[k] = payload[k];
|
129 | if (stateDependencies.current[k]) {
|
130 | shouldUpdateState = true;
|
131 | }
|
132 | }
|
133 | if (shouldUpdateState || config.suspense) {
|
134 | rerender({});
|
135 | }
|
136 | }, []);
|
137 |
|
138 | const unmountedRef = useRef(false);
|
139 | const keyRef = useRef(key);
|
140 | const boundMutate = useCallback((data, shouldRevalidate) => {
|
141 | return mutate(key, data, shouldRevalidate);
|
142 | }, [key]);
|
143 |
|
144 | const revalidate = useCallback(async (revalidateOpts = {}) => {
|
145 | if (!key || !fn)
|
146 | return false;
|
147 | if (unmountedRef.current)
|
148 | return false;
|
149 | revalidateOpts = Object.assign({ dedupe: false }, revalidateOpts);
|
150 | let loading = true;
|
151 | let shouldDeduping = typeof CONCURRENT_PROMISES[key] !== 'undefined' && revalidateOpts.dedupe;
|
152 |
|
153 | try {
|
154 | dispatch({
|
155 | isValidating: true
|
156 | });
|
157 | let newData;
|
158 | let startAt;
|
159 | if (shouldDeduping) {
|
160 |
|
161 |
|
162 | startAt = CONCURRENT_PROMISES_TS[key];
|
163 | newData = await CONCURRENT_PROMISES[key];
|
164 | }
|
165 | else {
|
166 |
|
167 |
|
168 |
|
169 |
|
170 |
|
171 |
|
172 |
|
173 |
|
174 | if (CONCURRENT_PROMISES[key]) {
|
175 |
|
176 |
|
177 | MUTATION_TS[key] = Date.now() - 1;
|
178 | }
|
179 |
|
180 |
|
181 | if (config.loadingTimeout && !cache.get(key)) {
|
182 | setTimeout(() => {
|
183 | if (loading)
|
184 | config.onLoadingSlow(key, config);
|
185 | }, config.loadingTimeout);
|
186 | }
|
187 | if (fnArgs !== null) {
|
188 | CONCURRENT_PROMISES[key] = fn(...fnArgs);
|
189 | }
|
190 | else {
|
191 | CONCURRENT_PROMISES[key] = fn(key);
|
192 | }
|
193 | CONCURRENT_PROMISES_TS[key] = startAt = Date.now();
|
194 | newData = await CONCURRENT_PROMISES[key];
|
195 | setTimeout(() => {
|
196 | delete CONCURRENT_PROMISES[key];
|
197 | delete CONCURRENT_PROMISES_TS[key];
|
198 | }, config.dedupingInterval);
|
199 |
|
200 |
|
201 | config.onSuccess(newData, key, config);
|
202 | }
|
203 |
|
204 |
|
205 |
|
206 | if (MUTATION_TS[key] && startAt <= MUTATION_TS[key]) {
|
207 | dispatch({ isValidating: false });
|
208 | return false;
|
209 | }
|
210 | cache.set(key, newData, false);
|
211 | cache.set(keyErr, undefined, false);
|
212 |
|
213 | const newState = {
|
214 | isValidating: false
|
215 | };
|
216 | if (typeof stateRef.current.error !== 'undefined') {
|
217 |
|
218 | newState.error = undefined;
|
219 | }
|
220 | if (config.compare(stateRef.current.data, newData)) {
|
221 |
|
222 |
|
223 | }
|
224 | else {
|
225 |
|
226 | newState.data = newData;
|
227 | }
|
228 |
|
229 | dispatch(newState);
|
230 | if (!shouldDeduping) {
|
231 |
|
232 | broadcastState(key, newData, undefined);
|
233 | }
|
234 | }
|
235 | catch (err) {
|
236 | delete CONCURRENT_PROMISES[key];
|
237 | delete CONCURRENT_PROMISES_TS[key];
|
238 | cache.set(keyErr, err, false);
|
239 |
|
240 |
|
241 | if (stateRef.current.error !== err) {
|
242 |
|
243 | dispatch({
|
244 | isValidating: false,
|
245 | error: err
|
246 | });
|
247 | if (!shouldDeduping) {
|
248 |
|
249 | broadcastState(key, undefined, err);
|
250 | }
|
251 | }
|
252 |
|
253 | config.onError(err, key, config);
|
254 | if (config.shouldRetryOnError) {
|
255 |
|
256 | const retryCount = (revalidateOpts.retryCount || 0) + 1;
|
257 | config.onErrorRetry(err, key, config, revalidate, Object.assign({ dedupe: true }, revalidateOpts, { retryCount }));
|
258 | }
|
259 | }
|
260 | loading = false;
|
261 | return true;
|
262 | }, [key]);
|
263 |
|
264 | useIsomorphicLayoutEffect(() => {
|
265 | if (!key)
|
266 | return undefined;
|
267 |
|
268 | unmountedRef.current = false;
|
269 |
|
270 |
|
271 |
|
272 | const currentHookData = stateRef.current.data;
|
273 | const latestKeyedData = cache.get(key) || config.initialData;
|
274 |
|
275 | if (keyRef.current !== key ||
|
276 | !config.compare(currentHookData, latestKeyedData)) {
|
277 | dispatch({ data: latestKeyedData });
|
278 | keyRef.current = key;
|
279 | }
|
280 |
|
281 | const softRevalidate = () => revalidate({ dedupe: true });
|
282 |
|
283 | if (!config.initialData) {
|
284 | if (typeof latestKeyedData !== 'undefined' &&
|
285 | !IS_SERVER &&
|
286 | window['requestIdleCallback']) {
|
287 |
|
288 |
|
289 | window['requestIdleCallback'](softRevalidate);
|
290 | }
|
291 | else {
|
292 | softRevalidate();
|
293 | }
|
294 | }
|
295 |
|
296 | let onFocus;
|
297 | if (config.revalidateOnFocus) {
|
298 |
|
299 |
|
300 | onFocus = throttle(softRevalidate, config.focusThrottleInterval);
|
301 | if (!FOCUS_REVALIDATORS[key]) {
|
302 | FOCUS_REVALIDATORS[key] = [onFocus];
|
303 | }
|
304 | else {
|
305 | FOCUS_REVALIDATORS[key].push(onFocus);
|
306 | }
|
307 | }
|
308 |
|
309 | const onUpdate = (shouldRevalidate = true, updatedData, updatedError, dedupe = true) => {
|
310 |
|
311 | const newState = {};
|
312 | let needUpdate = false;
|
313 | if (typeof updatedData !== 'undefined' &&
|
314 | !config.compare(stateRef.current.data, updatedData)) {
|
315 | newState.data = updatedData;
|
316 | needUpdate = true;
|
317 | }
|
318 |
|
319 |
|
320 | if (stateRef.current.error !== updatedError) {
|
321 | newState.error = updatedError;
|
322 | needUpdate = true;
|
323 | }
|
324 | if (needUpdate) {
|
325 | dispatch(newState);
|
326 | }
|
327 | if (shouldRevalidate) {
|
328 | if (dedupe) {
|
329 | return softRevalidate();
|
330 | }
|
331 | else {
|
332 | return revalidate();
|
333 | }
|
334 | }
|
335 | return false;
|
336 | };
|
337 |
|
338 | if (!CACHE_REVALIDATORS[key]) {
|
339 | CACHE_REVALIDATORS[key] = [onUpdate];
|
340 | }
|
341 | else {
|
342 | CACHE_REVALIDATORS[key].push(onUpdate);
|
343 | }
|
344 |
|
345 | let reconnect = null;
|
346 | if (!IS_SERVER && window.addEventListener && config.revalidateOnReconnect) {
|
347 | window.addEventListener('online', (reconnect = softRevalidate));
|
348 | }
|
349 | return () => {
|
350 |
|
351 | dispatch = () => null;
|
352 |
|
353 | unmountedRef.current = true;
|
354 | if (onFocus && FOCUS_REVALIDATORS[key]) {
|
355 | const revalidators = FOCUS_REVALIDATORS[key];
|
356 | const index = revalidators.indexOf(onFocus);
|
357 | if (index >= 0) {
|
358 |
|
359 |
|
360 | revalidators[index] = revalidators[revalidators.length - 1];
|
361 | revalidators.pop();
|
362 | }
|
363 | }
|
364 | if (CACHE_REVALIDATORS[key]) {
|
365 | const revalidators = CACHE_REVALIDATORS[key];
|
366 | const index = revalidators.indexOf(onUpdate);
|
367 | if (index >= 0) {
|
368 | revalidators[index] = revalidators[revalidators.length - 1];
|
369 | revalidators.pop();
|
370 | }
|
371 | }
|
372 | if (!IS_SERVER && window.removeEventListener && reconnect !== null) {
|
373 | window.removeEventListener('online', reconnect);
|
374 | }
|
375 | };
|
376 | }, [key, revalidate]);
|
377 |
|
378 | useIsomorphicLayoutEffect(() => {
|
379 | let timer = null;
|
380 | const tick = async () => {
|
381 | if (!stateRef.current.error &&
|
382 | (config.refreshWhenHidden || isDocumentVisible()) &&
|
383 | (config.refreshWhenOffline || isOnline())) {
|
384 |
|
385 |
|
386 |
|
387 | await revalidate({ dedupe: true });
|
388 | }
|
389 | if (config.refreshInterval) {
|
390 | timer = setTimeout(tick, config.refreshInterval);
|
391 | }
|
392 | };
|
393 | if (config.refreshInterval) {
|
394 | timer = setTimeout(tick, config.refreshInterval);
|
395 | }
|
396 | return () => {
|
397 | if (timer)
|
398 | clearTimeout(timer);
|
399 | };
|
400 | }, [
|
401 | config.refreshInterval,
|
402 | config.refreshWhenHidden,
|
403 | config.refreshWhenOffline,
|
404 | revalidate
|
405 | ]);
|
406 |
|
407 | if (config.suspense) {
|
408 | if (IS_SERVER)
|
409 | throw new Error('Suspense on server side is not yet supported!');
|
410 |
|
411 |
|
412 |
|
413 | let latestData = cache.get(key);
|
414 | let latestError = cache.get(keyErr);
|
415 | if (typeof latestData === 'undefined' &&
|
416 | typeof latestError === 'undefined') {
|
417 |
|
418 | if (!CONCURRENT_PROMISES[key]) {
|
419 |
|
420 |
|
421 | revalidate();
|
422 | }
|
423 | if (CONCURRENT_PROMISES[key] &&
|
424 | typeof CONCURRENT_PROMISES[key].then === 'function') {
|
425 |
|
426 | throw CONCURRENT_PROMISES[key];
|
427 | }
|
428 |
|
429 | latestData = CONCURRENT_PROMISES[key];
|
430 | }
|
431 | if (typeof latestData === 'undefined' && latestError) {
|
432 |
|
433 | throw latestError;
|
434 | }
|
435 |
|
436 |
|
437 | return {
|
438 | error: latestError,
|
439 | data: latestData,
|
440 | revalidate,
|
441 | mutate: boundMutate,
|
442 | isValidating: stateRef.current.isValidating
|
443 | };
|
444 | }
|
445 |
|
446 |
|
447 | return useMemo(() => {
|
448 | const state = { revalidate, mutate: boundMutate };
|
449 | Object.defineProperties(state, {
|
450 | error: {
|
451 |
|
452 |
|
453 |
|
454 | get: function () {
|
455 | stateDependencies.current.error = true;
|
456 | return stateRef.current.error;
|
457 | }
|
458 | },
|
459 | data: {
|
460 | get: function () {
|
461 | stateDependencies.current.data = true;
|
462 | return stateRef.current.data;
|
463 | }
|
464 | },
|
465 | isValidating: {
|
466 | get: function () {
|
467 | stateDependencies.current.isValidating = true;
|
468 | return stateRef.current.isValidating;
|
469 | }
|
470 | }
|
471 | });
|
472 | return state;
|
473 | }, [revalidate]);
|
474 | }
|
475 | const SWRConfig = SWRConfigContext.Provider;
|
476 | export { trigger, mutate, SWRConfig };
|
477 | export default useSWR;
|