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