12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034 |
- import { useEffect, useLayoutEffect, createContext, useContext, useState, createElement, useRef, useCallback, useDebugValue } from 'react';
- /*! *****************************************************************************
- Copyright (c) Microsoft Corporation.
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- PERFORMANCE OF THIS SOFTWARE.
- ***************************************************************************** */
- function __awaiter(thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- }
- function __generator(thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- }
- var noop = function () { };
- // Using noop() as the undefined value as undefined can possibly be replaced
- // by something else. Prettier ignore and extra parentheses are necessary here
- // to ensure that tsc doesn't remove the __NOINLINE__ comment.
- // prettier-ignore
- var UNDEFINED = ( /*#__NOINLINE__*/noop());
- var OBJECT = Object;
- var isUndefined = function (v) { return v === UNDEFINED; };
- var isFunction = function (v) { return typeof v == 'function'; };
- var mergeObjects = function (a, b) { return OBJECT.assign({}, a, b); };
- var STR_UNDEFINED = 'undefined';
- // NOTE: Use function to guarantee it's re-evaluated between jsdom and node runtime for tests.
- var hasWindow = function () { return typeof window != STR_UNDEFINED; };
- var hasDocument = function () { return typeof document != STR_UNDEFINED; };
- var hasRequestAnimationFrame = function () {
- return hasWindow() && typeof window['requestAnimationFrame'] != STR_UNDEFINED;
- };
- // use WeakMap to store the object->key mapping
- // so the objects can be garbage collected.
- // WeakMap uses a hashtable under the hood, so the lookup
- // complexity is almost O(1).
- var table = new WeakMap();
- // counter of the key
- var counter = 0;
- // A stable hash implementation that supports:
- // - Fast and ensures unique hash properties
- // - Handles unserializable values
- // - Handles object key ordering
- // - Generates short results
- //
- // This is not a serialization function, and the result is not guaranteed to be
- // parsible.
- var stableHash = function (arg) {
- var type = typeof arg;
- var constructor = arg && arg.constructor;
- var isDate = constructor == Date;
- var result;
- var index;
- if (OBJECT(arg) === arg && !isDate && constructor != RegExp) {
- // Object/function, not null/date/regexp. Use WeakMap to store the id first.
- // If it's already hashed, directly return the result.
- result = table.get(arg);
- if (result)
- return result;
- // Store the hash first for circular reference detection before entering the
- // recursive `stableHash` calls.
- // For other objects like set and map, we use this id directly as the hash.
- result = ++counter + '~';
- table.set(arg, result);
- if (constructor == Array) {
- // Array.
- result = '@';
- for (index = 0; index < arg.length; index++) {
- result += stableHash(arg[index]) + ',';
- }
- table.set(arg, result);
- }
- if (constructor == OBJECT) {
- // Object, sort keys.
- result = '#';
- var keys = OBJECT.keys(arg).sort();
- while (!isUndefined((index = keys.pop()))) {
- if (!isUndefined(arg[index])) {
- result += index + ':' + stableHash(arg[index]) + ',';
- }
- }
- table.set(arg, result);
- }
- }
- else {
- result = isDate
- ? arg.toJSON()
- : type == 'symbol'
- ? arg.toString()
- : type == 'string'
- ? JSON.stringify(arg)
- : '' + arg;
- }
- return result;
- };
- /**
- * Due to bug https://bugs.chromium.org/p/chromium/issues/detail?id=678075,
- * it's not reliable to detect if the browser is currently online or offline
- * based on `navigator.onLine`.
- * As a work around, we always assume it's online on first load, and change
- * the status upon `online` or `offline` events.
- */
- var online = true;
- var isOnline = function () { return online; };
- var hasWin = hasWindow();
- var hasDoc = hasDocument();
- // For node and React Native, `add/removeEventListener` doesn't exist on window.
- var onWindowEvent = hasWin && window.addEventListener
- ? window.addEventListener.bind(window)
- : noop;
- var onDocumentEvent = hasDoc ? document.addEventListener.bind(document) : noop;
- var offWindowEvent = hasWin && window.removeEventListener
- ? window.removeEventListener.bind(window)
- : noop;
- var offDocumentEvent = hasDoc
- ? document.removeEventListener.bind(document)
- : noop;
- var isVisible = function () {
- var visibilityState = hasDoc && document.visibilityState;
- return isUndefined(visibilityState) || visibilityState !== 'hidden';
- };
- var initFocus = function (callback) {
- // focus revalidate
- onDocumentEvent('visibilitychange', callback);
- onWindowEvent('focus', callback);
- return function () {
- offDocumentEvent('visibilitychange', callback);
- offWindowEvent('focus', callback);
- };
- };
- var initReconnect = function (callback) {
- // revalidate on reconnected
- var onOnline = function () {
- online = true;
- callback();
- };
- // nothing to revalidate, just update the status
- var onOffline = function () {
- online = false;
- };
- onWindowEvent('online', onOnline);
- onWindowEvent('offline', onOffline);
- return function () {
- offWindowEvent('online', onOnline);
- offWindowEvent('offline', onOffline);
- };
- };
- var preset = {
- isOnline: isOnline,
- isVisible: isVisible
- };
- var defaultConfigOptions = {
- initFocus: initFocus,
- initReconnect: initReconnect
- };
- var IS_SERVER = !hasWindow() || 'Deno' in window;
- // Polyfill requestAnimationFrame
- var rAF = function (f) {
- return hasRequestAnimationFrame() ? window['requestAnimationFrame'](f) : setTimeout(f, 1);
- };
- // React currently throws a warning when using useLayoutEffect on the server.
- // To get around it, we can conditionally useEffect on the server (no-op) and
- // useLayoutEffect in the browser.
- var useIsomorphicLayoutEffect = IS_SERVER ? useEffect : useLayoutEffect;
- // This assignment is to extend the Navigator type to use effectiveType.
- var navigatorConnection = typeof navigator !== 'undefined' &&
- navigator.connection;
- // Adjust the config based on slow connection status (<= 70Kbps).
- var slowConnection = !IS_SERVER &&
- navigatorConnection &&
- (['slow-2g', '2g'].includes(navigatorConnection.effectiveType) ||
- navigatorConnection.saveData);
- var serialize = function (key) {
- if (isFunction(key)) {
- try {
- key = key();
- }
- catch (err) {
- // dependencies not ready
- key = '';
- }
- }
- var args = [].concat(key);
- // If key is not falsy, or not an empty array, hash it.
- key =
- typeof key == 'string'
- ? key
- : (Array.isArray(key) ? key.length : key)
- ? stableHash(key)
- : '';
- var infoKey = key ? '$swr$' + key : '';
- return [key, args, infoKey];
- };
- // Global state used to deduplicate requests and store listeners
- var SWRGlobalState = new WeakMap();
- var FOCUS_EVENT = 0;
- var RECONNECT_EVENT = 1;
- var MUTATE_EVENT = 2;
- var broadcastState = function (cache, key, data, error, isValidating, revalidate, broadcast) {
- if (broadcast === void 0) { broadcast = true; }
- var _a = SWRGlobalState.get(cache), EVENT_REVALIDATORS = _a[0], STATE_UPDATERS = _a[1], FETCH = _a[3];
- var revalidators = EVENT_REVALIDATORS[key];
- var updaters = STATE_UPDATERS[key];
- // Cache was populated, update states of all hooks.
- if (broadcast && updaters) {
- for (var i = 0; i < updaters.length; ++i) {
- updaters[i](data, error, isValidating);
- }
- }
- // If we also need to revalidate, only do it for the first hook.
- if (revalidate) {
- // Invalidate the key by deleting the concurrent request markers so new
- // requests will not be deduped.
- delete FETCH[key];
- if (revalidators && revalidators[0]) {
- return revalidators[0](MUTATE_EVENT).then(function () {
- return cache.get(key);
- });
- }
- }
- return cache.get(key);
- };
- // Global timestamp.
- var __timestamp = 0;
- var getTimestamp = function () { return ++__timestamp; };
- var internalMutate = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return __awaiter(void 0, void 0, void 0, function () {
- var cache, _key, _data, _opts, options, populateCache, revalidate, rollbackOnError, optimisticData, _a, key, keyInfo, _b, MUTATION, data, error, beforeMutationTs, hasOptimisticData, rollbackData, res;
- return __generator(this, function (_c) {
- switch (_c.label) {
- case 0:
- cache = args[0], _key = args[1], _data = args[2], _opts = args[3];
- options = typeof _opts === 'boolean' ? { revalidate: _opts } : _opts || {};
- populateCache = options.populateCache !== false;
- revalidate = options.revalidate !== false;
- rollbackOnError = options.rollbackOnError !== false;
- optimisticData = options.optimisticData;
- _a = serialize(_key), key = _a[0], keyInfo = _a[2];
- if (!key)
- return [2 /*return*/];
- _b = SWRGlobalState.get(cache), MUTATION = _b[2];
- // If there is no new data provided, revalidate the key with current state.
- if (args.length < 3) {
- // Revalidate and broadcast state.
- return [2 /*return*/, broadcastState(cache, key, cache.get(key), UNDEFINED, UNDEFINED, revalidate, populateCache)];
- }
- data = _data;
- beforeMutationTs = getTimestamp();
- MUTATION[key] = [beforeMutationTs, 0];
- hasOptimisticData = !isUndefined(optimisticData);
- rollbackData = cache.get(key);
- // Do optimistic data update.
- if (hasOptimisticData) {
- cache.set(key, optimisticData);
- broadcastState(cache, key, optimisticData);
- }
- if (isFunction(data)) {
- // `data` is a function, call it passing current cache value.
- try {
- data = data(cache.get(key));
- }
- catch (err) {
- // If it throws an error synchronously, we shouldn't update the cache.
- error = err;
- }
- }
- if (!(data && isFunction(data.then))) return [3 /*break*/, 2];
- return [4 /*yield*/, data.catch(function (err) {
- error = err;
- })
- // Check if other mutations have occurred since we've started this mutation.
- // If there's a race we don't update cache or broadcast the change,
- // just return the data.
- ];
- case 1:
- // This means that the mutation is async, we need to check timestamps to
- // avoid race conditions.
- data = _c.sent();
- // Check if other mutations have occurred since we've started this mutation.
- // If there's a race we don't update cache or broadcast the change,
- // just return the data.
- if (beforeMutationTs !== MUTATION[key][0]) {
- if (error)
- throw error;
- return [2 /*return*/, data];
- }
- else if (error && hasOptimisticData && rollbackOnError) {
- // Rollback. Always populate the cache in this case.
- populateCache = true;
- data = rollbackData;
- cache.set(key, rollbackData);
- }
- _c.label = 2;
- case 2:
- if (populateCache) {
- if (!error) {
- // Only update cached data if there's no error. Data can be `undefined` here.
- cache.set(key, data);
- }
- // Always update or reset the error.
- cache.set(keyInfo, mergeObjects(cache.get(keyInfo), { error: error }));
- }
- // Reset the timestamp to mark the mutation has ended.
- MUTATION[key][1] = getTimestamp();
- return [4 /*yield*/, broadcastState(cache, key, data, error, UNDEFINED, revalidate, populateCache)
- // Throw error or return data
- ];
- case 3:
- res = _c.sent();
- // Throw error or return data
- if (error)
- throw error;
- return [2 /*return*/, populateCache ? res : data];
- }
- });
- });
- };
- var revalidateAllKeys = function (revalidators, type) {
- for (var key in revalidators) {
- if (revalidators[key][0])
- revalidators[key][0](type);
- }
- };
- var initCache = function (provider, options) {
- // The global state for a specific provider will be used to deduplicate
- // requests and store listeners. As well as a mutate function that bound to
- // the cache.
- // Provider's global state might be already initialized. Let's try to get the
- // global state associated with the provider first.
- if (!SWRGlobalState.has(provider)) {
- var opts = mergeObjects(defaultConfigOptions, options);
- // If there's no global state bound to the provider, create a new one with the
- // new mutate function.
- var EVENT_REVALIDATORS = {};
- var mutate = internalMutate.bind(UNDEFINED, provider);
- var unmount = noop;
- // Update the state if it's new, or the provider has been extended.
- SWRGlobalState.set(provider, [EVENT_REVALIDATORS, {}, {}, {}, mutate]);
- // This is a new provider, we need to initialize it and setup DOM events
- // listeners for `focus` and `reconnect` actions.
- if (!IS_SERVER) {
- // When listening to the native events for auto revalidations,
- // we intentionally put a delay (setTimeout) here to make sure they are
- // fired after immediate JavaScript executions, which can possibly be
- // React's state updates.
- // This avoids some unnecessary revalidations such as
- // https://github.com/vercel/swr/issues/1680.
- var releaseFocus_1 = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT)));
- var releaseReconnect_1 = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT)));
- unmount = function () {
- releaseFocus_1 && releaseFocus_1();
- releaseReconnect_1 && releaseReconnect_1();
- // When un-mounting, we need to remove the cache provider from the state
- // storage too because it's a side-effect. Otherwise when re-mounting we
- // will not re-register those event listeners.
- SWRGlobalState.delete(provider);
- };
- }
- // We might want to inject an extra layer on top of `provider` in the future,
- // such as key serialization, auto GC, etc.
- // For now, it's just a `Map` interface without any modifications.
- return [provider, mutate, unmount];
- }
- return [provider, SWRGlobalState.get(provider)[4]];
- };
- // error retry
- var onErrorRetry = function (_, __, config, revalidate, opts) {
- var maxRetryCount = config.errorRetryCount;
- var currentRetryCount = opts.retryCount;
- // Exponential backoff
- var timeout = ~~((Math.random() + 0.5) *
- (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;
- if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) {
- return;
- }
- setTimeout(revalidate, timeout, opts);
- };
- // Default cache provider
- var _a = initCache(new Map()), cache = _a[0], mutate = _a[1];
- // Default config
- var defaultConfig = mergeObjects({
- // events
- onLoadingSlow: noop,
- onSuccess: noop,
- onError: noop,
- onErrorRetry: onErrorRetry,
- onDiscarded: noop,
- // switches
- revalidateOnFocus: true,
- revalidateOnReconnect: true,
- revalidateIfStale: true,
- shouldRetryOnError: true,
- // timeouts
- errorRetryInterval: slowConnection ? 10000 : 5000,
- focusThrottleInterval: 5 * 1000,
- dedupingInterval: 2 * 1000,
- loadingTimeout: slowConnection ? 5000 : 3000,
- // providers
- compare: function (currentData, newData) {
- return stableHash(currentData) == stableHash(newData);
- },
- isPaused: function () { return false; },
- cache: cache,
- mutate: mutate,
- fallback: {}
- },
- // use web preset by default
- preset);
- var mergeConfigs = function (a, b) {
- // Need to create a new object to avoid mutating the original here.
- var v = mergeObjects(a, b);
- // If two configs are provided, merge their `use` and `fallback` options.
- if (b) {
- var u1 = a.use, f1 = a.fallback;
- var u2 = b.use, f2 = b.fallback;
- if (u1 && u2) {
- v.use = u1.concat(u2);
- }
- if (f1 && f2) {
- v.fallback = mergeObjects(f1, f2);
- }
- }
- return v;
- };
- var SWRConfigContext = createContext({});
- var SWRConfig$1 = function (props) {
- var value = props.value;
- // Extend parent context values and middleware.
- var extendedConfig = mergeConfigs(useContext(SWRConfigContext), value);
- // Should not use the inherited provider.
- var provider = value && value.provider;
- // Use a lazy initialized state to create the cache on first access.
- var cacheContext = useState(function () {
- return provider
- ? initCache(provider(extendedConfig.cache || cache), value)
- : UNDEFINED;
- })[0];
- // Override the cache if a new provider is given.
- if (cacheContext) {
- extendedConfig.cache = cacheContext[0];
- extendedConfig.mutate = cacheContext[1];
- }
- // Unsubscribe events.
- useIsomorphicLayoutEffect(function () { return (cacheContext ? cacheContext[2] : UNDEFINED); }, []);
- return createElement(SWRConfigContext.Provider, mergeObjects(props, {
- value: extendedConfig
- }));
- };
- /**
- * An implementation of state with dependency-tracking.
- */
- var useStateWithDeps = function (state, unmountedRef) {
- var rerender = useState({})[1];
- var stateRef = useRef(state);
- // If a state property (data, error or isValidating) is accessed by the render
- // function, we mark the property as a dependency so if it is updated again
- // in the future, we trigger a rerender.
- // This is also known as dependency-tracking.
- var stateDependenciesRef = useRef({
- data: false,
- error: false,
- isValidating: false
- });
- /**
- * @param payload To change stateRef, pass the values explicitly to setState:
- * @example
- * ```js
- * setState({
- * isValidating: false
- * data: newData // set data to newData
- * error: undefined // set error to undefined
- * })
- *
- * setState({
- * isValidating: false
- * data: undefined // set data to undefined
- * error: err // set error to err
- * })
- * ```
- */
- var setState = useCallback(function (payload) {
- var shouldRerender = false;
- var currentState = stateRef.current;
- for (var _ in payload) {
- var k = _;
- // If the property has changed, update the state and mark rerender as
- // needed.
- if (currentState[k] !== payload[k]) {
- currentState[k] = payload[k];
- // If the property is accessed by the component, a rerender should be
- // triggered.
- if (stateDependenciesRef.current[k]) {
- shouldRerender = true;
- }
- }
- }
- if (shouldRerender && !unmountedRef.current) {
- rerender({});
- }
- },
- // config.suspense isn't allowed to change during the lifecycle
- // eslint-disable-next-line react-hooks/exhaustive-deps
- []);
- // Always update the state reference.
- useIsomorphicLayoutEffect(function () {
- stateRef.current = state;
- });
- return [stateRef, stateDependenciesRef.current, setState];
- };
- var normalize = function (args) {
- return isFunction(args[1])
- ? [args[0], args[1], args[2] || {}]
- : [args[0], null, (args[1] === null ? args[2] : args[1]) || {}];
- };
- var useSWRConfig = function () {
- return mergeObjects(defaultConfig, useContext(SWRConfigContext));
- };
- // It's tricky to pass generic types as parameters, so we just directly override
- // the types here.
- var withArgs = function (hook) {
- return function useSWRArgs() {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- // Get the default and inherited configuration.
- var fallbackConfig = useSWRConfig();
- // Normalize arguments.
- var _a = normalize(args), key = _a[0], fn = _a[1], _config = _a[2];
- // Merge configurations.
- var config = mergeConfigs(fallbackConfig, _config);
- // Apply middleware
- var next = hook;
- var use = config.use;
- if (use) {
- for (var i = use.length; i-- > 0;) {
- next = use[i](next);
- }
- }
- return next(key, fn || config.fetcher, config);
- };
- };
- // Add a callback function to a list of keyed callback functions and return
- // the unsubscribe function.
- var subscribeCallback = function (key, callbacks, callback) {
- var keyedRevalidators = callbacks[key] || (callbacks[key] = []);
- keyedRevalidators.push(callback);
- return function () {
- var index = keyedRevalidators.indexOf(callback);
- if (index >= 0) {
- // O(1): faster than splice
- keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1];
- keyedRevalidators.pop();
- }
- };
- };
- var WITH_DEDUPE = { dedupe: true };
- var useSWRHandler = function (_key, fetcher, config) {
- var cache = config.cache, compare = config.compare, fallbackData = config.fallbackData, suspense = config.suspense, revalidateOnMount = config.revalidateOnMount, refreshInterval = config.refreshInterval, refreshWhenHidden = config.refreshWhenHidden, refreshWhenOffline = config.refreshWhenOffline;
- var _a = SWRGlobalState.get(cache), EVENT_REVALIDATORS = _a[0], STATE_UPDATERS = _a[1], MUTATION = _a[2], FETCH = _a[3];
- // `key` is the identifier of the SWR `data` state, `keyInfo` holds extra
- // states such as `error` and `isValidating` inside,
- // all of them are derived from `_key`.
- // `fnArgs` is an array of arguments parsed from the key, which will be passed
- // to the fetcher.
- var _b = serialize(_key), key = _b[0], fnArgs = _b[1], keyInfo = _b[2];
- // If it's the initial render of this hook.
- var initialMountedRef = useRef(false);
- // If the hook is unmounted already. This will be used to prevent some effects
- // to be called after unmounting.
- var unmountedRef = useRef(false);
- // Refs to keep the key and config.
- var keyRef = useRef(key);
- var fetcherRef = useRef(fetcher);
- var configRef = useRef(config);
- var getConfig = function () { return configRef.current; };
- var isActive = function () { return getConfig().isVisible() && getConfig().isOnline(); };
- var patchFetchInfo = function (info) {
- return cache.set(keyInfo, mergeObjects(cache.get(keyInfo), info));
- };
- // Get the current state that SWR should return.
- var cached = cache.get(key);
- var fallback = isUndefined(fallbackData)
- ? config.fallback[key]
- : fallbackData;
- var data = isUndefined(cached) ? fallback : cached;
- var info = cache.get(keyInfo) || {};
- var error = info.error;
- // - Suspense mode and there's stale data for the initial render.
- // - Not suspense mode and there is no fallback data and `revalidateIfStale` is enabled.
- // - `revalidateIfStale` is enabled but `data` is not defined.
- var shouldRevalidateOnMount = function () {
- // If `revalidateOnMount` is set, we take the value directly.
- if (!isUndefined(revalidateOnMount))
- return revalidateOnMount;
- // If it's paused, we skip revalidation.
- if (getConfig().isPaused())
- return false;
- return suspense
- ? // Under suspense mode, it will always fetch on render if there is no
- // stale data so no need to revalidate immediately on mount again.
- !isUndefined(data)
- : // If there is no stale data, we need to revalidate on mount;
- // If `revalidateIfStale` is set to true, we will always revalidate.
- isUndefined(data) || config.revalidateIfStale;
- };
- // Resolve the current validating state.
- var resolveValidating = function () {
- if (!key || !fetcher)
- return false;
- if (info.isValidating)
- return true;
- // If it's not mounted yet and it should revalidate on mount, revalidate.
- return !initialMountedRef.current && shouldRevalidateOnMount();
- };
- var isValidating = resolveValidating();
- var _c = useStateWithDeps({
- data: data,
- error: error,
- isValidating: isValidating
- }, unmountedRef), stateRef = _c[0], stateDependencies = _c[1], setState = _c[2];
- // The revalidation function is a carefully crafted wrapper of the original
- // `fetcher`, to correctly handle the many edge cases.
- var revalidate = useCallback(function (revalidateOpts) { return __awaiter(void 0, void 0, void 0, function () {
- var currentFetcher, newData, startAt, loading, opts, shouldStartNewRequest, isCurrentKeyMounted, cleanupState, newState, finishRequestAndUpdateState, mutationInfo, err_1;
- var _a;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- currentFetcher = fetcherRef.current;
- if (!key ||
- !currentFetcher ||
- unmountedRef.current ||
- getConfig().isPaused()) {
- return [2 /*return*/, false];
- }
- loading = true;
- opts = revalidateOpts || {};
- shouldStartNewRequest = !FETCH[key] || !opts.dedupe;
- isCurrentKeyMounted = function () {
- return !unmountedRef.current &&
- key === keyRef.current &&
- initialMountedRef.current;
- };
- cleanupState = function () {
- // Check if it's still the same request before deleting.
- var requestInfo = FETCH[key];
- if (requestInfo && requestInfo[1] === startAt) {
- delete FETCH[key];
- }
- };
- newState = { isValidating: false };
- finishRequestAndUpdateState = function () {
- patchFetchInfo({ isValidating: false });
- // We can only set state if it's safe (still mounted with the same key).
- if (isCurrentKeyMounted()) {
- setState(newState);
- }
- };
- // Start fetching. Change the `isValidating` state, update the cache.
- patchFetchInfo({
- isValidating: true
- });
- setState({ isValidating: true });
- _b.label = 1;
- case 1:
- _b.trys.push([1, 3, , 4]);
- if (shouldStartNewRequest) {
- // Tell all other hooks to change the `isValidating` state.
- broadcastState(cache, key, stateRef.current.data, stateRef.current.error, true);
- // If no cache being rendered currently (it shows a blank page),
- // we trigger the loading slow event.
- if (config.loadingTimeout && !cache.get(key)) {
- setTimeout(function () {
- if (loading && isCurrentKeyMounted()) {
- getConfig().onLoadingSlow(key, config);
- }
- }, config.loadingTimeout);
- }
- // Start the request and save the timestamp.
- FETCH[key] = [currentFetcher.apply(void 0, fnArgs), getTimestamp()];
- }
- _a = FETCH[key], newData = _a[0], startAt = _a[1];
- return [4 /*yield*/, newData];
- case 2:
- newData = _b.sent();
- if (shouldStartNewRequest) {
- // If the request isn't interrupted, clean it up after the
- // deduplication interval.
- setTimeout(cleanupState, config.dedupingInterval);
- }
- // If there're other ongoing request(s), started after the current one,
- // we need to ignore the current one to avoid possible race conditions:
- // req1------------------>res1 (current one)
- // req2---------------->res2
- // the request that fired later will always be kept.
- // The timestamp maybe be `undefined` or a number
- if (!FETCH[key] || FETCH[key][1] !== startAt) {
- if (shouldStartNewRequest) {
- if (isCurrentKeyMounted()) {
- getConfig().onDiscarded(key);
- }
- }
- return [2 /*return*/, false];
- }
- // Clear error.
- patchFetchInfo({
- error: UNDEFINED
- });
- newState.error = UNDEFINED;
- mutationInfo = MUTATION[key];
- if (!isUndefined(mutationInfo) &&
- // case 1
- (startAt <= mutationInfo[0] ||
- // case 2
- startAt <= mutationInfo[1] ||
- // case 3
- mutationInfo[1] === 0)) {
- finishRequestAndUpdateState();
- if (shouldStartNewRequest) {
- if (isCurrentKeyMounted()) {
- getConfig().onDiscarded(key);
- }
- }
- return [2 /*return*/, false];
- }
- // Deep compare with latest state to avoid extra re-renders.
- // For local state, compare and assign.
- if (!compare(stateRef.current.data, newData)) {
- newState.data = newData;
- }
- else {
- // data and newData are deeply equal
- // it should be safe to broadcast the stale data
- newState.data = stateRef.current.data;
- // At the end of this function, `brocastState` invokes the `onStateUpdate` function,
- // which takes care of avoiding the re-render
- }
- // For global state, it's possible that the key has changed.
- // https://github.com/vercel/swr/pull/1058
- if (!compare(cache.get(key), newData)) {
- cache.set(key, newData);
- }
- // Trigger the successful callback if it's the original request.
- if (shouldStartNewRequest) {
- if (isCurrentKeyMounted()) {
- getConfig().onSuccess(newData, key, config);
- }
- }
- return [3 /*break*/, 4];
- case 3:
- err_1 = _b.sent();
- cleanupState();
- // Not paused, we continue handling the error. Otherwise discard it.
- if (!getConfig().isPaused()) {
- // Get a new error, don't use deep comparison for errors.
- patchFetchInfo({ error: err_1 });
- newState.error = err_1;
- // Error event and retry logic. Only for the actual request, not
- // deduped ones.
- if (shouldStartNewRequest && isCurrentKeyMounted()) {
- getConfig().onError(err_1, key, config);
- if ((typeof config.shouldRetryOnError === 'boolean' &&
- config.shouldRetryOnError) ||
- (isFunction(config.shouldRetryOnError) &&
- config.shouldRetryOnError(err_1))) {
- // When retrying, dedupe is always enabled
- if (isActive()) {
- // If it's active, stop. It will auto revalidate when refocusing
- // or reconnecting.
- getConfig().onErrorRetry(err_1, key, config, revalidate, {
- retryCount: (opts.retryCount || 0) + 1,
- dedupe: true
- });
- }
- }
- }
- }
- return [3 /*break*/, 4];
- case 4:
- // Mark loading as stopped.
- loading = false;
- // Update the current hook's state.
- finishRequestAndUpdateState();
- // Here is the source of the request, need to tell all other hooks to
- // update their states.
- if (isCurrentKeyMounted() && shouldStartNewRequest) {
- broadcastState(cache, key, newState.data, newState.error, false);
- }
- return [2 /*return*/, true];
- }
- });
- }); },
- // `setState` is immutable, and `eventsCallback`, `fnArgs`, `keyInfo`,
- // and `keyValidating` are depending on `key`, so we can exclude them from
- // the deps array.
- //
- // FIXME:
- // `fn` and `config` might be changed during the lifecycle,
- // but they might be changed every render like this.
- // `useSWR('key', () => fetch('/api/'), { suspense: true })`
- // So we omit the values from the deps array
- // even though it might cause unexpected behaviors.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [key]);
- // Similar to the global mutate, but bound to the current cache and key.
- // `cache` isn't allowed to change during the lifecycle.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- var boundMutate = useCallback(
- // By using `bind` we don't need to modify the size of the rest arguments.
- internalMutate.bind(UNDEFINED, cache, function () { return keyRef.current; }),
- // eslint-disable-next-line react-hooks/exhaustive-deps
- []);
- // Always update fetcher and config refs.
- useIsomorphicLayoutEffect(function () {
- fetcherRef.current = fetcher;
- configRef.current = config;
- });
- // After mounted or key changed.
- useIsomorphicLayoutEffect(function () {
- if (!key)
- return;
- // Not the initial render.
- var keyChanged = initialMountedRef.current;
- var softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE);
- // Expose state updater to global event listeners. So we can update hook's
- // internal state from the outside.
- var onStateUpdate = function (updatedData, updatedError, updatedIsValidating) {
- setState(mergeObjects({
- error: updatedError,
- isValidating: updatedIsValidating
- },
- // Since `setState` only shallowly compares states, we do a deep
- // comparison here.
- compare(stateRef.current.data, updatedData)
- ? UNDEFINED
- : {
- data: updatedData
- }));
- };
- // Expose revalidators to global event listeners. So we can trigger
- // revalidation from the outside.
- var nextFocusRevalidatedAt = 0;
- var onRevalidate = function (type) {
- if (type == FOCUS_EVENT) {
- var now = Date.now();
- if (getConfig().revalidateOnFocus &&
- now > nextFocusRevalidatedAt &&
- isActive()) {
- nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval;
- softRevalidate();
- }
- }
- else if (type == RECONNECT_EVENT) {
- if (getConfig().revalidateOnReconnect && isActive()) {
- softRevalidate();
- }
- }
- else if (type == MUTATE_EVENT) {
- return revalidate();
- }
- return;
- };
- var unsubUpdate = subscribeCallback(key, STATE_UPDATERS, onStateUpdate);
- var unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);
- // Mark the component as mounted and update corresponding refs.
- unmountedRef.current = false;
- keyRef.current = key;
- initialMountedRef.current = true;
- // When `key` updates, reset the state to the initial value
- // and trigger a rerender if necessary.
- if (keyChanged) {
- setState({
- data: data,
- error: error,
- isValidating: isValidating
- });
- }
- // Trigger a revalidation.
- if (shouldRevalidateOnMount()) {
- if (isUndefined(data) || IS_SERVER) {
- // Revalidate immediately.
- softRevalidate();
- }
- else {
- // Delay the revalidate if we have data to return so we won't block
- // rendering.
- rAF(softRevalidate);
- }
- }
- return function () {
- // Mark it as unmounted.
- unmountedRef.current = true;
- unsubUpdate();
- unsubEvents();
- };
- }, [key, revalidate]);
- // Polling
- useIsomorphicLayoutEffect(function () {
- var timer;
- function next() {
- // Use the passed interval
- // ...or invoke the function with the updated data to get the interval
- var interval = isFunction(refreshInterval)
- ? refreshInterval(data)
- : refreshInterval;
- // We only start next interval if `refreshInterval` is not 0, and:
- // - `force` is true, which is the start of polling
- // - or `timer` is not 0, which means the effect wasn't canceled
- if (interval && timer !== -1) {
- timer = setTimeout(execute, interval);
- }
- }
- function execute() {
- // Check if it's OK to execute:
- // Only revalidate when the page is visible, online and not errored.
- if (!stateRef.current.error &&
- (refreshWhenHidden || getConfig().isVisible()) &&
- (refreshWhenOffline || getConfig().isOnline())) {
- revalidate(WITH_DEDUPE).then(next);
- }
- else {
- // Schedule next interval to check again.
- next();
- }
- }
- next();
- return function () {
- if (timer) {
- clearTimeout(timer);
- timer = -1;
- }
- };
- }, [refreshInterval, refreshWhenHidden, refreshWhenOffline, revalidate]);
- // Display debug info in React DevTools.
- useDebugValue(data);
- // In Suspense mode, we can't return the empty `data` state.
- // If there is `error`, the `error` needs to be thrown to the error boundary.
- // If there is no `error`, the `revalidation` promise needs to be thrown to
- // the suspense boundary.
- if (suspense && isUndefined(data) && key) {
- // Always update fetcher and config refs even with the Suspense mode.
- fetcherRef.current = fetcher;
- configRef.current = config;
- throw isUndefined(error) ? revalidate(WITH_DEDUPE) : error;
- }
- return {
- mutate: boundMutate,
- get data() {
- stateDependencies.data = true;
- return data;
- },
- get error() {
- stateDependencies.error = true;
- return error;
- },
- get isValidating() {
- stateDependencies.isValidating = true;
- return isValidating;
- }
- };
- };
- var SWRConfig = OBJECT.defineProperty(SWRConfig$1, 'default', {
- value: defaultConfig
- });
- var unstable_serialize = function (key) { return serialize(key)[0]; };
- var useSWR = withArgs(useSWRHandler);
- // useSWR
- export { SWRConfig, useSWR as default, mutate, unstable_serialize, useSWRConfig };
|