New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

swr

Package Overview
Dependencies
Maintainers
6
Versions
164
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

swr - npm Package Compare versions

Comparing version 2.0.0-rc.0 to 2.0.0-rc.1

_internal/dist/index.d.ts

836

_internal/dist/index.esm.js
import React, { useEffect, useLayoutEffect, createContext, useContext, useMemo, useState, createElement, useRef, useCallback } from 'react';
// Global state used to deduplicate requests and store listeners
var SWRGlobalState = new WeakMap();
const SWRGlobalState = new WeakMap();
var _typeof$1 = function(obj) {
"@swc/helpers - typeof";
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
var EMPTY_CACHE = {};
var noop = function() {};
const EMPTY_CACHE = {};
const noop = ()=>{};
// Using noop() as the undefined value as undefined can be replaced

@@ -16,30 +12,23 @@ // by something else. Prettier ignore and extra parentheses are necessary here

// 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";
const UNDEFINED = /*#__NOINLINE__*/ noop();
const OBJECT = Object;
const isUndefined = (v)=>v === UNDEFINED;
const isFunction = (v)=>typeof v == 'function';
const mergeObjects = (a, b)=>({
...a,
...b
});
const STR_UNDEFINED = 'undefined';
// NOTE: Use the function to guarantee it's re-evaluated between jsdom and node runtime for tests.
var isWindowDefined = (typeof window === "undefined" ? "undefined" : _typeof$1(window)) != STR_UNDEFINED;
var isDocumentDefined = (typeof document === "undefined" ? "undefined" : _typeof$1(document)) != STR_UNDEFINED;
var hasRequestAnimationFrame = function() {
return isWindowDefined && _typeof$1(window["requestAnimationFrame"]) != STR_UNDEFINED;
};
var createCacheHelper = function(cache, key) {
var state = SWRGlobalState.get(cache);
const isWindowDefined = typeof window != STR_UNDEFINED;
const isDocumentDefined = typeof document != STR_UNDEFINED;
const hasRequestAnimationFrame = ()=>isWindowDefined && typeof window['requestAnimationFrame'] != STR_UNDEFINED;
const createCacheHelper = (cache, key)=>{
const state = SWRGlobalState.get(cache);
return [
// Getter
function() {
return cache.get(key) || EMPTY_CACHE;
},
()=>cache.get(key) || EMPTY_CACHE,
// Setter
function(info) {
var prev = cache.get(key);
(info)=>{
const prev = cache.get(key);
state[5](key, mergeObjects(prev, info), prev || EMPTY_CACHE);

@@ -52,6 +41,2 @@ },

var _typeof = function(obj) {
"@swc/helpers - typeof";
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
// use WeakMap to store the object->key mapping

@@ -61,5 +46,5 @@ // so the objects can be garbage collected.

// complexity is almost O(1).
var table = new WeakMap();
const table = new WeakMap();
// counter of the key
var counter = 0;
let counter = 0;
// A stable hash implementation that supports:

@@ -73,8 +58,8 @@ // - Fast and ensures unique hash properties

// parsable.
var stableHash = function(arg) {
var type = typeof arg === "undefined" ? "undefined" : _typeof(arg);
var constructor = arg && arg.constructor;
var isDate = constructor == Date;
var result;
var index;
const stableHash = (arg)=>{
const type = typeof arg;
const constructor = arg && arg.constructor;
const isDate = constructor == Date;
let result;
let index;
if (OBJECT(arg) === arg && !isDate && constructor != RegExp) {

@@ -88,9 +73,9 @@ // Object/function, not null/date/regexp. Use WeakMap to store the id first.

// For other objects like set and map, we use this id directly as the hash.
result = ++counter + "~";
result = ++counter + '~';
table.set(arg, result);
if (constructor == Array) {
// Array.
result = "@";
result = '@';
for(index = 0; index < arg.length; index++){
result += stableHash(arg[index]) + ",";
result += stableHash(arg[index]) + ',';
}

@@ -101,7 +86,7 @@ table.set(arg, result);

// Object, sort keys.
result = "#";
var keys = OBJECT.keys(arg).sort();
result = '#';
const keys = OBJECT.keys(arg).sort();
while(!isUndefined(index = keys.pop())){
if (!isUndefined(arg[index])) {
result += index + ":" + stableHash(arg[index]) + ",";
result += index + ':' + stableHash(arg[index]) + ',';
}

@@ -112,3 +97,3 @@ }

} else {
result = isDate ? arg.toJSON() : type == "symbol" ? arg.toString() : type == "string" ? JSON.stringify(arg) : "" + arg;
result = isDate ? arg.toJSON() : type == 'symbol' ? arg.toString() : type == 'string' ? JSON.stringify(arg) : '' + arg;
}

@@ -124,8 +109,6 @@ return result;

* the status upon `online` or `offline` events.
*/ var online = true;
var isOnline = function() {
return online;
};
*/ let online = true;
const isOnline = ()=>online;
// For node and React Native, `add/removeEventListener` doesn't exist on window.
var ref$1 = isWindowDefined && window.addEventListener ? [
const [onWindowEvent, offWindowEvent] = isWindowDefined && window.addEventListener ? [
window.addEventListener.bind(window),

@@ -136,23 +119,23 @@ window.removeEventListener.bind(window)

noop
], onWindowEvent = ref$1[0], offWindowEvent = ref$1[1];
var isVisible = function() {
var visibilityState = isDocumentDefined && document.visibilityState;
return isUndefined(visibilityState) || visibilityState !== "hidden";
];
const isVisible = ()=>{
const visibilityState = isDocumentDefined && document.visibilityState;
return isUndefined(visibilityState) || visibilityState !== 'hidden';
};
var initFocus = function(callback) {
const initFocus = (callback)=>{
// focus revalidate
if (isDocumentDefined) {
document.addEventListener("visibilitychange", callback);
document.addEventListener('visibilitychange', callback);
}
onWindowEvent("focus", callback);
return function() {
onWindowEvent('focus', callback);
return ()=>{
if (isDocumentDefined) {
document.removeEventListener("visibilitychange", callback);
document.removeEventListener('visibilitychange', callback);
}
offWindowEvent("focus", callback);
offWindowEvent('focus', callback);
};
};
var initReconnect = function(callback) {
const initReconnect = (callback)=>{
// revalidate on reconnected
var onOnline = function() {
const onOnline = ()=>{
online = true;

@@ -162,40 +145,38 @@ callback();

// nothing to revalidate, just update the status
var onOffline = function() {
const onOffline = ()=>{
online = false;
};
onWindowEvent("online", onOnline);
onWindowEvent("offline", onOffline);
return function() {
offWindowEvent("online", onOnline);
offWindowEvent("offline", onOffline);
onWindowEvent('online', onOnline);
onWindowEvent('offline', onOffline);
return ()=>{
offWindowEvent('online', onOnline);
offWindowEvent('offline', onOffline);
};
};
var preset = {
isOnline: isOnline,
isVisible: isVisible
const preset = {
isOnline,
isVisible
};
var defaultConfigOptions = {
initFocus: initFocus,
initReconnect: initReconnect
const defaultConfigOptions = {
initFocus,
initReconnect
};
var IS_REACT_LEGACY = !React.useId;
var IS_SERVER = !isWindowDefined || "Deno" in window;
const IS_REACT_LEGACY = !React.useId;
const IS_SERVER = !isWindowDefined || 'Deno' in window;
// Polyfill requestAnimationFrame
var rAF = function(f) {
return hasRequestAnimationFrame() ? window["requestAnimationFrame"](f) : setTimeout(f, 1);
};
const rAF = (f)=>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;
const useIsomorphicLayoutEffect = IS_SERVER ? useEffect : useLayoutEffect;
// This assignment is to extend the Navigator type to use effectiveType.
var navigatorConnection = typeof navigator !== "undefined" && navigator.connection;
const navigatorConnection = typeof navigator !== 'undefined' && navigator.connection;
// Adjust the config based on slow connection status (<= 70Kbps).
var slowConnection = !IS_SERVER && navigatorConnection && ([
"slow-2g",
"2g"
const slowConnection = !IS_SERVER && navigatorConnection && ([
'slow-2g',
'2g'
].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData);
var serialize = function(key) {
const serialize = (key)=>{
if (isFunction(key)) {

@@ -206,3 +187,3 @@ try {

// dependencies not ready
key = "";
key = '';
}

@@ -212,5 +193,5 @@ }

// array of values.
var args = key;
const args = 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) : "";
key = typeof key == 'string' ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : '';
return [

@@ -223,10 +204,8 @@ key,

// Global timestamp.
var __timestamp = 0;
var getTimestamp = function() {
return ++__timestamp;
};
let __timestamp = 0;
const getTimestamp = ()=>++__timestamp;
var FOCUS_EVENT = 0;
var RECONNECT_EVENT = 1;
var MUTATE_EVENT = 2;
const FOCUS_EVENT = 0;
const RECONNECT_EVENT = 1;
const MUTATE_EVENT = 2;

@@ -240,317 +219,156 @@ var constants = {

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
async function internalMutate(...args) {
const [cache, _key, _data, _opts] = args;
// When passing as a boolean, it's explicitly used to disable/enable
// revalidation.
const options = mergeObjects({
populateCache: true,
throwOnError: true
}, typeof _opts === 'boolean' ? {
revalidate: _opts
} : _opts || {});
let populateCache = options.populateCache;
const rollbackOnErrorOption = options.rollbackOnError;
let optimisticData = options.optimisticData;
const revalidate = options.revalidate !== false;
const rollbackOnError = (error)=>{
return typeof rollbackOnErrorOption === 'function' ? rollbackOnErrorOption(error) : rollbackOnErrorOption !== false;
};
const throwOnError = options.throwOnError;
// If the second argument is a key filter, return the mutation results for all
// filtered keys.
if (isFunction(_key)) {
const keyFilter = _key;
const matchedKeys = [];
const it = cache.keys();
for(let keyIt = it.next(); !keyIt.done; keyIt = it.next()){
const key = keyIt.value;
if (// Skip the special useSWRInfinite keys.
!key.startsWith('$inf$') && keyFilter(cache.get(key)._k)) {
matchedKeys.push(key);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
var __generator = undefined && undefined.__generator || function(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
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
]);
};
}
return Promise.all(matchedKeys.map(mutateByKey));
}
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;
return mutateByKey(_key);
async function mutateByKey(_k) {
// Serialize key
const [key] = serialize(_k);
if (!key) return;
const [get, set] = createCacheHelper(cache, key);
const [EVENT_REVALIDATORS, MUTATION, FETCH] = SWRGlobalState.get(cache);
const revalidators = EVENT_REVALIDATORS[key];
const startRevalidate = ()=>{
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(()=>get().data);
}
}
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
return get().data;
};
}
};
function internalMutate() {
return _internalMutate.apply(this, arguments);
}
function _internalMutate() {
_internalMutate = _asyncToGenerator(function() {
var _len, args, _key, cache, _key1, _data, _opts, options, _tmp, _tmp1, _tmp2, populateCache, optimisticData, revalidate, rollbackOnError, throwOnError, keyFilter, matchedKeys, it, keyIt, key;
var _arguments = arguments;
function mutateByKey(_k) {
return _mutateByKey.apply(this, arguments);
// If there is no new data provided, revalidate the key with current state.
if (args.length < 3) {
// Revalidate and broadcast state.
return startRevalidate();
}
function _mutateByKey() {
_mutateByKey = _asyncToGenerator(function(_k) {
var ref, key, ref1, get, set, ref2, EVENT_REVALIDATORS, MUTATION, FETCH, revalidators, startRevalidate, data, error, beforeMutationTs, hasOptimisticData, state, displayedData, committedData, _tmp, _tmp1, _tmp2, res, _tmp3;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
ref = serialize(_k), key = ref[0];
if (!key) return [
2
];
ref1 = createCacheHelper(cache, key), get = ref1[0], set = ref1[1];
ref2 = SWRGlobalState.get(cache), EVENT_REVALIDATORS = ref2[0], MUTATION = ref2[1], FETCH = ref2[2];
revalidators = EVENT_REVALIDATORS[key];
startRevalidate = function() {
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 get().data;
});
}
}
return get().data;
};
// If there is no new data provided, revalidate the key with current state.
if (args.length < 3) {
// Revalidate and broadcast state.
return [
2,
startRevalidate()
];
}
data = _data;
beforeMutationTs = getTimestamp();
MUTATION[key] = [
beforeMutationTs,
0
];
hasOptimisticData = !isUndefined(optimisticData);
state = get();
displayedData = state.data;
committedData = isUndefined(state._c) ? displayedData : state._c;
_tmp = {};
// Do optimistic data update.
if (hasOptimisticData) {
optimisticData = isFunction(optimisticData) ? optimisticData(committedData) : optimisticData;
// When we set optimistic data, backup the current committedData data in `_c`.
set((_tmp.data = optimisticData, _tmp._c = committedData, _tmp));
}
if (isFunction(data)) {
// `data` is a function, call it passing current cache value.
try {
data = data(committedData);
} catch (err) {
// If it throws an error synchronously, we shouldn't update the cache.
error = err;
}
}
if (!(data && isFunction(data.then))) return [
3,
2
];
return [
4,
data.catch(function(err) {
error = err;
})
];
case 1:
// This means that the mutation is async, we need to check timestamps to
// avoid race conditions.
data = _state.sent();
_tmp1 = {};
// 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,
data
];
} else if (error && hasOptimisticData && rollbackOnError) {
// Rollback. Always populate the cache in this case but without
// transforming the data.
populateCache = true;
data = committedData;
// Reset data to be the latest committed data, and clear the `_c` value.
set((_tmp1.data = data, _tmp1._c = UNDEFINED, _tmp1));
}
_state.label = 2;
case 2:
_tmp2 = {};
// If we should write back the cache after request.
if (populateCache) {
if (!error) {
// Transform the result into data.
if (isFunction(populateCache)) {
data = populateCache(data, committedData);
}
// Only update cached data if there's no error. Data can be `undefined` here.
set((_tmp2.data = data, _tmp2._c = UNDEFINED, _tmp2));
}
}
// Reset the timestamp to mark the mutation has ended.
MUTATION[key][1] = getTimestamp();
return [
4,
startRevalidate()
];
case 3:
res = _state.sent();
_tmp3 = {};
// The mutation and revalidation are ended, we can clear it since the data is
// not an optimistic value anymore.
set((_tmp3._c = UNDEFINED, _tmp3));
// Throw error or return data
if (error) {
if (throwOnError) throw error;
return [
2
];
}
return [
2,
populateCache ? res : data
];
}
});
let data = _data;
let error;
// Update global timestamps.
const beforeMutationTs = getTimestamp();
MUTATION[key] = [
beforeMutationTs,
0
];
const hasOptimisticData = !isUndefined(optimisticData);
const state = get();
// `displayedData` is the current value on screen. It could be the optimistic value
// that is going to be overridden by a `committedData`, or get reverted back.
// `committedData` is the validated value that comes from a fetch or mutation.
const displayedData = state.data;
const currentData = state._c;
const committedData = isUndefined(currentData) ? displayedData : currentData;
// Do optimistic data update.
if (hasOptimisticData) {
optimisticData = isFunction(optimisticData) ? optimisticData(committedData) : optimisticData;
// When we set optimistic data, backup the current committedData data in `_c`.
set({
data: optimisticData,
_c: committedData
});
return _mutateByKey.apply(this, arguments);
}
return __generator(this, function(_state) {
for(_len = _arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = _arguments[_key];
if (isFunction(data)) {
// `data` is a function, call it passing current cache value.
try {
data = data(committedData);
} catch (err) {
// If it throws an error synchronously, we shouldn't update the cache.
error = err;
}
cache = args[0], _key1 = args[1], _data = args[2], _opts = args[3];
_tmp = {};
_tmp1 = {};
_tmp2 = {};
options = mergeObjects((_tmp.populateCache = true, _tmp.throwOnError = true, _tmp), typeof _opts === "boolean" ? (_tmp1.revalidate = _opts, _tmp1) : _opts || _tmp2);
populateCache = options.populateCache;
optimisticData = options.optimisticData;
revalidate = options.revalidate !== false;
rollbackOnError = options.rollbackOnError !== false;
throwOnError = options.throwOnError;
// If the second argument is a key filter, return the mutation results for all
// filtered keys.
if (isFunction(_key1)) {
keyFilter = _key1;
matchedKeys = [];
it = cache.keys();
for(keyIt = it.next(); !keyIt.done; keyIt = it.next()){
key = keyIt.value;
if (// Skip the special useSWRInfinite keys.
!key.startsWith("$inf$") && keyFilter(cache.get(key)._k)) {
matchedKeys.push(key);
}
}
// `data` is a promise/thenable, resolve the final data first.
if (data && isFunction(data.then)) {
// This means that the mutation is async, we need to check timestamps to
// avoid race conditions.
data = await data.catch((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.
if (beforeMutationTs !== MUTATION[key][0]) {
if (error) throw error;
return data;
} else if (error && hasOptimisticData && rollbackOnError(error)) {
// Rollback. Always populate the cache in this case but without
// transforming the data.
populateCache = true;
data = committedData;
// Reset data to be the latest committed data, and clear the `_c` value.
set({
data,
_c: UNDEFINED
});
}
}
// If we should write back the cache after request.
if (populateCache) {
if (!error) {
// Transform the result into data.
if (isFunction(populateCache)) {
data = populateCache(data, committedData);
}
return [
2,
Promise.all(matchedKeys.map(mutateByKey))
];
// Only update cached data if there's no error. Data can be `undefined` here.
set({
data,
_c: UNDEFINED
});
}
return [
2,
mutateByKey(_key1)
];
}
// Reset the timestamp to mark the mutation has ended.
MUTATION[key][1] = getTimestamp();
// Update existing SWR Hooks' internal states:
const res = await startRevalidate();
// The mutation and revalidation are ended, we can clear it since the data is
// not an optimistic value anymore.
set({
_c: UNDEFINED
});
});
return _internalMutate.apply(this, arguments);
// Throw error or return data
if (error) {
if (throwOnError) throw error;
return;
}
return populateCache ? res : data;
}
}
var revalidateAllKeys = function(revalidators, type) {
for(var key in revalidators){
const revalidateAllKeys = (revalidators, type)=>{
for(const key in revalidators){
if (revalidators[key][0]) revalidators[key][0](type);
}
};
var initCache = function(provider, options) {
const initCache = (provider, options)=>{
// The global state for a specific provider will be used to deduplicate

@@ -562,22 +380,20 @@ // requests and store listeners. As well as a mutate function that is bound to

if (!SWRGlobalState.has(provider)) {
var opts = mergeObjects(defaultConfigOptions, options);
const 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;
var subscriptions = {};
var subscribe = function(key, callback) {
var subs = subscriptions[key] || [];
const EVENT_REVALIDATORS = {};
const mutate = internalMutate.bind(UNDEFINED, provider);
let unmount = noop;
const subscriptions = {};
const subscribe = (key, callback)=>{
const subs = subscriptions[key] || [];
subscriptions[key] = subs;
subs.push(callback);
return function() {
return subs.splice(subs.indexOf(callback), 1);
};
return ()=>subs.splice(subs.indexOf(callback), 1);
};
var setter = function(key, value, prev) {
const setter = (key, value, prev)=>{
provider.set(key, value);
var subs = subscriptions[key];
const subs = subscriptions[key];
if (subs) {
for(var i = subs.length; i--;){
for(let i = subs.length; i--;){
subs[i](prev, value);

@@ -587,3 +403,3 @@ }

};
var initProvider = function() {
const initProvider = ()=>{
if (!SWRGlobalState.has(provider)) {

@@ -607,5 +423,5 @@ // Update the state if it's new, or if the provider has been extended.

// https://github.com/vercel/swr/issues/1680.
var releaseFocus = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT)));
var releaseReconnect = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT)));
unmount = function() {
const releaseFocus = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT)));
const releaseReconnect = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT)));
unmount = ()=>{
releaseFocus && releaseFocus();

@@ -641,7 +457,7 @@ releaseReconnect && releaseReconnect();

// error retry
var onErrorRetry = function(_, __, config, revalidate, opts) {
var maxRetryCount = config.errorRetryCount;
var currentRetryCount = opts.retryCount;
const onErrorRetry = (_, __, config, revalidate, opts)=>{
const maxRetryCount = config.errorRetryCount;
const currentRetryCount = opts.retryCount;
// Exponential backoff
var timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;
const timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;
if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) {

@@ -652,9 +468,7 @@ return;

};
var compare = function(currentData, newData) {
return stableHash(currentData) == stableHash(newData);
};
const compare = (currentData, newData)=>stableHash(currentData) == stableHash(newData);
// Default cache provider
var ref = initCache(new Map()), cache = ref[0], mutate = ref[1];
const [cache, mutate] = initCache(new Map());
// Default config
var defaultConfig = mergeObjects({
const defaultConfig = mergeObjects({
// events

@@ -664,3 +478,3 @@ onLoadingSlow: noop,

onError: noop,
onErrorRetry: onErrorRetry,
onErrorRetry,
onDiscarded: noop,

@@ -678,8 +492,6 @@ // switches

// providers
compare: compare,
isPaused: function() {
return false;
},
cache: cache,
mutate: mutate,
compare,
isPaused: ()=>false,
cache,
mutate,
fallback: {}

@@ -689,9 +501,9 @@ }, // use web preset by default

var mergeConfigs = function(a, b) {
const mergeConfigs = (a, b)=>{
// Need to create a new object to avoid mutating the original here.
var v = mergeObjects(a, b);
const 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;
const { use: u1 , fallback: f1 } = a;
const { use: u2 , fallback: f2 } = b;
if (u1 && u2) {

@@ -707,10 +519,8 @@ v.use = u1.concat(u2);

var SWRConfigContext = createContext({});
var SWRConfig = function(props) {
var value = props.value;
var parentConfig = useContext(SWRConfigContext);
var isFunctionalConfig = isFunction(value);
var config = useMemo(function() {
return isFunctionalConfig ? value(parentConfig) : value;
}, [
const SWRConfigContext = createContext({});
const SWRConfig = (props)=>{
const { value } = props;
const parentConfig = useContext(SWRConfigContext);
const isFunctionalConfig = isFunction(value);
const config = useMemo(()=>isFunctionalConfig ? value(parentConfig) : value, [
isFunctionalConfig,

@@ -721,5 +531,3 @@ parentConfig,

// Extend parent context values and middleware.
var extendedConfig = useMemo(function() {
return isFunctionalConfig ? config : mergeConfigs(parentConfig, config);
}, [
const extendedConfig = useMemo(()=>isFunctionalConfig ? config : mergeConfigs(parentConfig, config), [
isFunctionalConfig,

@@ -730,7 +538,5 @@ parentConfig,

// Should not use the inherited provider.
var provider = config && config.provider;
const provider = config && config.provider;
// Use a lazy initialized state to create the cache on first access.
var ref = useState(function() {
return provider ? initCache(provider(extendedConfig.cache || cache), config) : UNDEFINED;
}), cacheContext = ref[0];
const [cacheContext] = useState(()=>provider ? initCache(provider(extendedConfig.cache || cache), config) : UNDEFINED);
// Override the cache if a new provider is given.

@@ -742,3 +548,3 @@ if (cacheContext) {

// Unsubscribe events.
useIsomorphicLayoutEffect(function() {
useIsomorphicLayoutEffect(()=>{
if (cacheContext) {

@@ -755,5 +561,5 @@ cacheContext[2] && cacheContext[2]();

// @ts-expect-error
var enableDevtools = isWindowDefined && window.__SWR_DEVTOOLS_USE__;
var use = enableDevtools ? window.__SWR_DEVTOOLS_USE__ : [];
var setupDevTools = function() {
const enableDevtools = isWindowDefined && window.__SWR_DEVTOOLS_USE__;
const use = enableDevtools ? window.__SWR_DEVTOOLS_USE__ : [];
const setupDevTools = ()=>{
if (enableDevtools) {

@@ -765,3 +571,3 @@ // @ts-expect-error

var normalize = function(args) {
const normalize = (args)=>{
return isFunction(args[1]) ? [

@@ -778,25 +584,21 @@ args[0],

var useSWRConfig = function() {
const useSWRConfig = ()=>{
return mergeObjects(defaultConfig, useContext(SWRConfigContext));
};
var preload = function(key_, fetcher) {
var key = serialize(key_)[0];
var ref = SWRGlobalState.get(cache), PRELOAD = ref[3];
const preload = (key_, fetcher)=>{
const key = serialize(key_)[0];
const [, , , PRELOAD] = SWRGlobalState.get(cache);
// Prevent preload to be called multiple times before used.
if (PRELOAD[key]) return PRELOAD[key];
var req = fetcher(key_);
const req = fetcher(key_);
PRELOAD[key] = req;
return req;
};
var middleware = function(useSWRNext) {
return function(key_, fetcher_, config) {
const middleware = (useSWRNext)=>(key_, fetcher_, config)=>{
// fetcher might be a sync function, so this should not be an async function
var fetcher = fetcher_ && function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
var key = serialize(key_)[0];
var ref = SWRGlobalState.get(cache), PRELOAD = ref[3];
var req = PRELOAD[key];
const fetcher = fetcher_ && ((...args)=>{
const key = serialize(key_)[0];
const [, , , PRELOAD] = SWRGlobalState.get(cache);
const req = PRELOAD[key];
if (req) {

@@ -806,28 +608,24 @@ delete PRELOAD[key];

}
return fetcher_.apply(void 0, args);
};
return fetcher_(...args);
});
return useSWRNext(key_, fetcher, config);
};
};
var BUILT_IN_MIDDLEWARE = use.concat(middleware);
const BUILT_IN_MIDDLEWARE = use.concat(middleware);
// It's tricky to pass generic types as parameters, so we just directly override
// the types here.
var withArgs = function(hook) {
return function useSWRArgs() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
const withArgs = (hook)=>{
return function useSWRArgs(...args) {
// Get the default and inherited configuration.
var fallbackConfig = useSWRConfig();
const fallbackConfig = useSWRConfig();
// Normalize arguments.
var ref = normalize(args), key = ref[0], fn = ref[1], _config = ref[2];
const [key, fn, _config] = normalize(args);
// Merge configurations.
var config = mergeConfigs(fallbackConfig, _config);
const config = mergeConfigs(fallbackConfig, _config);
// Apply middleware
var next = hook;
var use = config.use;
var middleware = (use || []).concat(BUILT_IN_MIDDLEWARE);
for(var i = middleware.length; i--;){
let next = hook;
const { use } = config;
const middleware = (use || []).concat(BUILT_IN_MIDDLEWARE);
for(let i = middleware.length; i--;){
next = middleware[i](next);

@@ -841,6 +639,6 @@ }

* An implementation of state with dependency-tracking.
*/ var useStateWithDeps = function(state) {
var rerender = useState({})[1];
var unmountedRef = useRef(false);
var stateRef = useRef(state);
*/ const useStateWithDeps = (state)=>{
const rerender = useState({})[1];
const unmountedRef = useRef(false);
const stateRef = useRef(state);
// If a state property (data, error, or isValidating) is accessed by the render

@@ -850,3 +648,3 @@ // function, we mark the property as a dependency so if it is updated again

// This is also known as dependency-tracking.
var stateDependenciesRef = useRef({
const stateDependenciesRef = useRef({
data: false,

@@ -872,7 +670,7 @@ error: false,

* ```
*/ var setState = useCallback(function(payload) {
var shouldRerender = false;
var currentState = stateRef.current;
for(var _ in payload){
var k = _;
*/ const setState = useCallback((payload)=>{
let shouldRerender = false;
const currentState = stateRef.current;
for(const _ in payload){
const k = _;
// If the property has changed, update the state and mark rerender as

@@ -893,5 +691,3 @@ // needed.

} else {
React.startTransition(function() {
return rerender({});
});
React.startTransition(()=>rerender({}));
}

@@ -902,5 +698,5 @@ }

[]);
useIsomorphicLayoutEffect(function() {
useIsomorphicLayoutEffect(()=>{
unmountedRef.current = false;
return function() {
return ()=>{
unmountedRef.current = true;

@@ -918,7 +714,7 @@ };

// the unsubscribe function.
var subscribeCallback = function(key, callbacks, callback) {
var keyedRevalidators = callbacks[key] || (callbacks[key] = []);
const subscribeCallback = (key, callbacks, callback)=>{
const keyedRevalidators = callbacks[key] || (callbacks[key] = []);
keyedRevalidators.push(callback);
return function() {
var index = keyedRevalidators.indexOf(callback);
return ()=>{
const index = keyedRevalidators.indexOf(callback);
if (index >= 0) {

@@ -932,27 +728,11 @@ // O(1): faster than splice

function _extends() {
_extends = Object.assign || function(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i];
for(var key in source){
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
// Create a custom hook with a middleware
var withMiddleware = function(useSWR, middleware) {
return function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
var ref = normalize(args), key = ref[0], fn = ref[1], config = ref[2];
var uses = (config.use || []).concat(middleware);
return useSWR(key, fn, _extends({}, config, {
const withMiddleware = (useSWR, middleware)=>{
return (...args)=>{
const [key, fn, config] = normalize(args);
const uses = (config.use || []).concat(middleware);
return useSWR(key, fn, {
...config,
use: uses
}));
});
};

@@ -959,0 +739,0 @@ };

@@ -1,3 +0,1 @@

Object.defineProperty(exports, '__esModule', { value: true });
var React = require('react');

@@ -10,10 +8,6 @@

// Global state used to deduplicate requests and store listeners
var SWRGlobalState = new WeakMap();
const SWRGlobalState = new WeakMap();
var _typeof$1 = function(obj) {
"@swc/helpers - typeof";
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
var EMPTY_CACHE = {};
var noop = function() {};
const EMPTY_CACHE = {};
const noop = ()=>{};
// Using noop() as the undefined value as undefined can be replaced

@@ -23,30 +17,23 @@ // by something else. Prettier ignore and extra parentheses are necessary here

// 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";
const UNDEFINED = /*#__NOINLINE__*/ noop();
const OBJECT = Object;
const isUndefined = (v)=>v === UNDEFINED;
const isFunction = (v)=>typeof v == 'function';
const mergeObjects = (a, b)=>({
...a,
...b
});
const STR_UNDEFINED = 'undefined';
// NOTE: Use the function to guarantee it's re-evaluated between jsdom and node runtime for tests.
var isWindowDefined = (typeof window === "undefined" ? "undefined" : _typeof$1(window)) != STR_UNDEFINED;
var isDocumentDefined = (typeof document === "undefined" ? "undefined" : _typeof$1(document)) != STR_UNDEFINED;
var hasRequestAnimationFrame = function() {
return isWindowDefined && _typeof$1(window["requestAnimationFrame"]) != STR_UNDEFINED;
};
var createCacheHelper = function(cache, key) {
var state = SWRGlobalState.get(cache);
const isWindowDefined = typeof window != STR_UNDEFINED;
const isDocumentDefined = typeof document != STR_UNDEFINED;
const hasRequestAnimationFrame = ()=>isWindowDefined && typeof window['requestAnimationFrame'] != STR_UNDEFINED;
const createCacheHelper = (cache, key)=>{
const state = SWRGlobalState.get(cache);
return [
// Getter
function() {
return cache.get(key) || EMPTY_CACHE;
},
()=>cache.get(key) || EMPTY_CACHE,
// Setter
function(info) {
var prev = cache.get(key);
(info)=>{
const prev = cache.get(key);
state[5](key, mergeObjects(prev, info), prev || EMPTY_CACHE);

@@ -59,6 +46,2 @@ },

var _typeof = function(obj) {
"@swc/helpers - typeof";
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
// use WeakMap to store the object->key mapping

@@ -68,5 +51,5 @@ // so the objects can be garbage collected.

// complexity is almost O(1).
var table = new WeakMap();
const table = new WeakMap();
// counter of the key
var counter = 0;
let counter = 0;
// A stable hash implementation that supports:

@@ -80,8 +63,8 @@ // - Fast and ensures unique hash properties

// parsable.
var stableHash = function(arg) {
var type = typeof arg === "undefined" ? "undefined" : _typeof(arg);
var constructor = arg && arg.constructor;
var isDate = constructor == Date;
var result;
var index;
const stableHash = (arg)=>{
const type = typeof arg;
const constructor = arg && arg.constructor;
const isDate = constructor == Date;
let result;
let index;
if (OBJECT(arg) === arg && !isDate && constructor != RegExp) {

@@ -95,9 +78,9 @@ // Object/function, not null/date/regexp. Use WeakMap to store the id first.

// For other objects like set and map, we use this id directly as the hash.
result = ++counter + "~";
result = ++counter + '~';
table.set(arg, result);
if (constructor == Array) {
// Array.
result = "@";
result = '@';
for(index = 0; index < arg.length; index++){
result += stableHash(arg[index]) + ",";
result += stableHash(arg[index]) + ',';
}

@@ -108,7 +91,7 @@ table.set(arg, result);

// Object, sort keys.
result = "#";
var keys = OBJECT.keys(arg).sort();
result = '#';
const keys = OBJECT.keys(arg).sort();
while(!isUndefined(index = keys.pop())){
if (!isUndefined(arg[index])) {
result += index + ":" + stableHash(arg[index]) + ",";
result += index + ':' + stableHash(arg[index]) + ',';
}

@@ -119,3 +102,3 @@ }

} else {
result = isDate ? arg.toJSON() : type == "symbol" ? arg.toString() : type == "string" ? JSON.stringify(arg) : "" + arg;
result = isDate ? arg.toJSON() : type == 'symbol' ? arg.toString() : type == 'string' ? JSON.stringify(arg) : '' + arg;
}

@@ -131,8 +114,6 @@ return result;

* the status upon `online` or `offline` events.
*/ var online = true;
var isOnline = function() {
return online;
};
*/ let online = true;
const isOnline = ()=>online;
// For node and React Native, `add/removeEventListener` doesn't exist on window.
var ref$1 = isWindowDefined && window.addEventListener ? [
const [onWindowEvent, offWindowEvent] = isWindowDefined && window.addEventListener ? [
window.addEventListener.bind(window),

@@ -143,23 +124,23 @@ window.removeEventListener.bind(window)

noop
], onWindowEvent = ref$1[0], offWindowEvent = ref$1[1];
var isVisible = function() {
var visibilityState = isDocumentDefined && document.visibilityState;
return isUndefined(visibilityState) || visibilityState !== "hidden";
];
const isVisible = ()=>{
const visibilityState = isDocumentDefined && document.visibilityState;
return isUndefined(visibilityState) || visibilityState !== 'hidden';
};
var initFocus = function(callback) {
const initFocus = (callback)=>{
// focus revalidate
if (isDocumentDefined) {
document.addEventListener("visibilitychange", callback);
document.addEventListener('visibilitychange', callback);
}
onWindowEvent("focus", callback);
return function() {
onWindowEvent('focus', callback);
return ()=>{
if (isDocumentDefined) {
document.removeEventListener("visibilitychange", callback);
document.removeEventListener('visibilitychange', callback);
}
offWindowEvent("focus", callback);
offWindowEvent('focus', callback);
};
};
var initReconnect = function(callback) {
const initReconnect = (callback)=>{
// revalidate on reconnected
var onOnline = function() {
const onOnline = ()=>{
online = true;

@@ -169,40 +150,38 @@ callback();

// nothing to revalidate, just update the status
var onOffline = function() {
const onOffline = ()=>{
online = false;
};
onWindowEvent("online", onOnline);
onWindowEvent("offline", onOffline);
return function() {
offWindowEvent("online", onOnline);
offWindowEvent("offline", onOffline);
onWindowEvent('online', onOnline);
onWindowEvent('offline', onOffline);
return ()=>{
offWindowEvent('online', onOnline);
offWindowEvent('offline', onOffline);
};
};
var preset = {
isOnline: isOnline,
isVisible: isVisible
const preset = {
isOnline,
isVisible
};
var defaultConfigOptions = {
initFocus: initFocus,
initReconnect: initReconnect
const defaultConfigOptions = {
initFocus,
initReconnect
};
var IS_REACT_LEGACY = !React__default["default"].useId;
var IS_SERVER = !isWindowDefined || "Deno" in window;
const IS_REACT_LEGACY = !React__default["default"].useId;
const IS_SERVER = !isWindowDefined || 'Deno' in window;
// Polyfill requestAnimationFrame
var rAF = function(f) {
return hasRequestAnimationFrame() ? window["requestAnimationFrame"](f) : setTimeout(f, 1);
};
const rAF = (f)=>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 ? React.useEffect : React.useLayoutEffect;
const useIsomorphicLayoutEffect = IS_SERVER ? React.useEffect : React.useLayoutEffect;
// This assignment is to extend the Navigator type to use effectiveType.
var navigatorConnection = typeof navigator !== "undefined" && navigator.connection;
const navigatorConnection = typeof navigator !== 'undefined' && navigator.connection;
// Adjust the config based on slow connection status (<= 70Kbps).
var slowConnection = !IS_SERVER && navigatorConnection && ([
"slow-2g",
"2g"
const slowConnection = !IS_SERVER && navigatorConnection && ([
'slow-2g',
'2g'
].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData);
var serialize = function(key) {
const serialize = (key)=>{
if (isFunction(key)) {

@@ -213,3 +192,3 @@ try {

// dependencies not ready
key = "";
key = '';
}

@@ -219,5 +198,5 @@ }

// array of values.
var args = key;
const args = 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) : "";
key = typeof key == 'string' ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : '';
return [

@@ -230,10 +209,8 @@ key,

// Global timestamp.
var __timestamp = 0;
var getTimestamp = function() {
return ++__timestamp;
};
let __timestamp = 0;
const getTimestamp = ()=>++__timestamp;
var FOCUS_EVENT = 0;
var RECONNECT_EVENT = 1;
var MUTATE_EVENT = 2;
const FOCUS_EVENT = 0;
const RECONNECT_EVENT = 1;
const MUTATE_EVENT = 2;

@@ -247,317 +224,156 @@ var constants = {

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
async function internalMutate(...args) {
const [cache, _key, _data, _opts] = args;
// When passing as a boolean, it's explicitly used to disable/enable
// revalidation.
const options = mergeObjects({
populateCache: true,
throwOnError: true
}, typeof _opts === 'boolean' ? {
revalidate: _opts
} : _opts || {});
let populateCache = options.populateCache;
const rollbackOnErrorOption = options.rollbackOnError;
let optimisticData = options.optimisticData;
const revalidate = options.revalidate !== false;
const rollbackOnError = (error)=>{
return typeof rollbackOnErrorOption === 'function' ? rollbackOnErrorOption(error) : rollbackOnErrorOption !== false;
};
const throwOnError = options.throwOnError;
// If the second argument is a key filter, return the mutation results for all
// filtered keys.
if (isFunction(_key)) {
const keyFilter = _key;
const matchedKeys = [];
const it = cache.keys();
for(let keyIt = it.next(); !keyIt.done; keyIt = it.next()){
const key = keyIt.value;
if (// Skip the special useSWRInfinite keys.
!key.startsWith('$inf$') && keyFilter(cache.get(key)._k)) {
matchedKeys.push(key);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
var __generator = undefined && undefined.__generator || function(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
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
]);
};
}
return Promise.all(matchedKeys.map(mutateByKey));
}
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;
return mutateByKey(_key);
async function mutateByKey(_k) {
// Serialize key
const [key] = serialize(_k);
if (!key) return;
const [get, set] = createCacheHelper(cache, key);
const [EVENT_REVALIDATORS, MUTATION, FETCH] = SWRGlobalState.get(cache);
const revalidators = EVENT_REVALIDATORS[key];
const startRevalidate = ()=>{
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(()=>get().data);
}
}
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
return get().data;
};
}
};
function internalMutate() {
return _internalMutate.apply(this, arguments);
}
function _internalMutate() {
_internalMutate = _asyncToGenerator(function() {
var _len, args, _key, cache, _key1, _data, _opts, options, _tmp, _tmp1, _tmp2, populateCache, optimisticData, revalidate, rollbackOnError, throwOnError, keyFilter, matchedKeys, it, keyIt, key;
var _arguments = arguments;
function mutateByKey(_k) {
return _mutateByKey.apply(this, arguments);
// If there is no new data provided, revalidate the key with current state.
if (args.length < 3) {
// Revalidate and broadcast state.
return startRevalidate();
}
function _mutateByKey() {
_mutateByKey = _asyncToGenerator(function(_k) {
var ref, key, ref1, get, set, ref2, EVENT_REVALIDATORS, MUTATION, FETCH, revalidators, startRevalidate, data, error, beforeMutationTs, hasOptimisticData, state, displayedData, committedData, _tmp, _tmp1, _tmp2, res, _tmp3;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
ref = serialize(_k), key = ref[0];
if (!key) return [
2
];
ref1 = createCacheHelper(cache, key), get = ref1[0], set = ref1[1];
ref2 = SWRGlobalState.get(cache), EVENT_REVALIDATORS = ref2[0], MUTATION = ref2[1], FETCH = ref2[2];
revalidators = EVENT_REVALIDATORS[key];
startRevalidate = function() {
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 get().data;
});
}
}
return get().data;
};
// If there is no new data provided, revalidate the key with current state.
if (args.length < 3) {
// Revalidate and broadcast state.
return [
2,
startRevalidate()
];
}
data = _data;
beforeMutationTs = getTimestamp();
MUTATION[key] = [
beforeMutationTs,
0
];
hasOptimisticData = !isUndefined(optimisticData);
state = get();
displayedData = state.data;
committedData = isUndefined(state._c) ? displayedData : state._c;
_tmp = {};
// Do optimistic data update.
if (hasOptimisticData) {
optimisticData = isFunction(optimisticData) ? optimisticData(committedData) : optimisticData;
// When we set optimistic data, backup the current committedData data in `_c`.
set((_tmp.data = optimisticData, _tmp._c = committedData, _tmp));
}
if (isFunction(data)) {
// `data` is a function, call it passing current cache value.
try {
data = data(committedData);
} catch (err) {
// If it throws an error synchronously, we shouldn't update the cache.
error = err;
}
}
if (!(data && isFunction(data.then))) return [
3,
2
];
return [
4,
data.catch(function(err) {
error = err;
})
];
case 1:
// This means that the mutation is async, we need to check timestamps to
// avoid race conditions.
data = _state.sent();
_tmp1 = {};
// 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,
data
];
} else if (error && hasOptimisticData && rollbackOnError) {
// Rollback. Always populate the cache in this case but without
// transforming the data.
populateCache = true;
data = committedData;
// Reset data to be the latest committed data, and clear the `_c` value.
set((_tmp1.data = data, _tmp1._c = UNDEFINED, _tmp1));
}
_state.label = 2;
case 2:
_tmp2 = {};
// If we should write back the cache after request.
if (populateCache) {
if (!error) {
// Transform the result into data.
if (isFunction(populateCache)) {
data = populateCache(data, committedData);
}
// Only update cached data if there's no error. Data can be `undefined` here.
set((_tmp2.data = data, _tmp2._c = UNDEFINED, _tmp2));
}
}
// Reset the timestamp to mark the mutation has ended.
MUTATION[key][1] = getTimestamp();
return [
4,
startRevalidate()
];
case 3:
res = _state.sent();
_tmp3 = {};
// The mutation and revalidation are ended, we can clear it since the data is
// not an optimistic value anymore.
set((_tmp3._c = UNDEFINED, _tmp3));
// Throw error or return data
if (error) {
if (throwOnError) throw error;
return [
2
];
}
return [
2,
populateCache ? res : data
];
}
});
let data = _data;
let error;
// Update global timestamps.
const beforeMutationTs = getTimestamp();
MUTATION[key] = [
beforeMutationTs,
0
];
const hasOptimisticData = !isUndefined(optimisticData);
const state = get();
// `displayedData` is the current value on screen. It could be the optimistic value
// that is going to be overridden by a `committedData`, or get reverted back.
// `committedData` is the validated value that comes from a fetch or mutation.
const displayedData = state.data;
const currentData = state._c;
const committedData = isUndefined(currentData) ? displayedData : currentData;
// Do optimistic data update.
if (hasOptimisticData) {
optimisticData = isFunction(optimisticData) ? optimisticData(committedData) : optimisticData;
// When we set optimistic data, backup the current committedData data in `_c`.
set({
data: optimisticData,
_c: committedData
});
return _mutateByKey.apply(this, arguments);
}
return __generator(this, function(_state) {
for(_len = _arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = _arguments[_key];
if (isFunction(data)) {
// `data` is a function, call it passing current cache value.
try {
data = data(committedData);
} catch (err) {
// If it throws an error synchronously, we shouldn't update the cache.
error = err;
}
cache = args[0], _key1 = args[1], _data = args[2], _opts = args[3];
_tmp = {};
_tmp1 = {};
_tmp2 = {};
options = mergeObjects((_tmp.populateCache = true, _tmp.throwOnError = true, _tmp), typeof _opts === "boolean" ? (_tmp1.revalidate = _opts, _tmp1) : _opts || _tmp2);
populateCache = options.populateCache;
optimisticData = options.optimisticData;
revalidate = options.revalidate !== false;
rollbackOnError = options.rollbackOnError !== false;
throwOnError = options.throwOnError;
// If the second argument is a key filter, return the mutation results for all
// filtered keys.
if (isFunction(_key1)) {
keyFilter = _key1;
matchedKeys = [];
it = cache.keys();
for(keyIt = it.next(); !keyIt.done; keyIt = it.next()){
key = keyIt.value;
if (// Skip the special useSWRInfinite keys.
!key.startsWith("$inf$") && keyFilter(cache.get(key)._k)) {
matchedKeys.push(key);
}
}
// `data` is a promise/thenable, resolve the final data first.
if (data && isFunction(data.then)) {
// This means that the mutation is async, we need to check timestamps to
// avoid race conditions.
data = await data.catch((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.
if (beforeMutationTs !== MUTATION[key][0]) {
if (error) throw error;
return data;
} else if (error && hasOptimisticData && rollbackOnError(error)) {
// Rollback. Always populate the cache in this case but without
// transforming the data.
populateCache = true;
data = committedData;
// Reset data to be the latest committed data, and clear the `_c` value.
set({
data,
_c: UNDEFINED
});
}
}
// If we should write back the cache after request.
if (populateCache) {
if (!error) {
// Transform the result into data.
if (isFunction(populateCache)) {
data = populateCache(data, committedData);
}
return [
2,
Promise.all(matchedKeys.map(mutateByKey))
];
// Only update cached data if there's no error. Data can be `undefined` here.
set({
data,
_c: UNDEFINED
});
}
return [
2,
mutateByKey(_key1)
];
}
// Reset the timestamp to mark the mutation has ended.
MUTATION[key][1] = getTimestamp();
// Update existing SWR Hooks' internal states:
const res = await startRevalidate();
// The mutation and revalidation are ended, we can clear it since the data is
// not an optimistic value anymore.
set({
_c: UNDEFINED
});
});
return _internalMutate.apply(this, arguments);
// Throw error or return data
if (error) {
if (throwOnError) throw error;
return;
}
return populateCache ? res : data;
}
}
var revalidateAllKeys = function(revalidators, type) {
for(var key in revalidators){
const revalidateAllKeys = (revalidators, type)=>{
for(const key in revalidators){
if (revalidators[key][0]) revalidators[key][0](type);
}
};
var initCache = function(provider, options) {
const initCache = (provider, options)=>{
// The global state for a specific provider will be used to deduplicate

@@ -569,22 +385,20 @@ // requests and store listeners. As well as a mutate function that is bound to

if (!SWRGlobalState.has(provider)) {
var opts = mergeObjects(defaultConfigOptions, options);
const 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;
var subscriptions = {};
var subscribe = function(key, callback) {
var subs = subscriptions[key] || [];
const EVENT_REVALIDATORS = {};
const mutate = internalMutate.bind(UNDEFINED, provider);
let unmount = noop;
const subscriptions = {};
const subscribe = (key, callback)=>{
const subs = subscriptions[key] || [];
subscriptions[key] = subs;
subs.push(callback);
return function() {
return subs.splice(subs.indexOf(callback), 1);
};
return ()=>subs.splice(subs.indexOf(callback), 1);
};
var setter = function(key, value, prev) {
const setter = (key, value, prev)=>{
provider.set(key, value);
var subs = subscriptions[key];
const subs = subscriptions[key];
if (subs) {
for(var i = subs.length; i--;){
for(let i = subs.length; i--;){
subs[i](prev, value);

@@ -594,3 +408,3 @@ }

};
var initProvider = function() {
const initProvider = ()=>{
if (!SWRGlobalState.has(provider)) {

@@ -614,5 +428,5 @@ // Update the state if it's new, or if the provider has been extended.

// https://github.com/vercel/swr/issues/1680.
var releaseFocus = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT)));
var releaseReconnect = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT)));
unmount = function() {
const releaseFocus = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, FOCUS_EVENT)));
const releaseReconnect = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, RECONNECT_EVENT)));
unmount = ()=>{
releaseFocus && releaseFocus();

@@ -648,7 +462,7 @@ releaseReconnect && releaseReconnect();

// error retry
var onErrorRetry = function(_, __, config, revalidate, opts) {
var maxRetryCount = config.errorRetryCount;
var currentRetryCount = opts.retryCount;
const onErrorRetry = (_, __, config, revalidate, opts)=>{
const maxRetryCount = config.errorRetryCount;
const currentRetryCount = opts.retryCount;
// Exponential backoff
var timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;
const timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;
if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) {

@@ -659,9 +473,7 @@ return;

};
var compare = function(currentData, newData) {
return stableHash(currentData) == stableHash(newData);
};
const compare = (currentData, newData)=>stableHash(currentData) == stableHash(newData);
// Default cache provider
var ref = initCache(new Map()), cache = ref[0], mutate = ref[1];
const [cache, mutate] = initCache(new Map());
// Default config
var defaultConfig = mergeObjects({
const defaultConfig = mergeObjects({
// events

@@ -671,3 +483,3 @@ onLoadingSlow: noop,

onError: noop,
onErrorRetry: onErrorRetry,
onErrorRetry,
onDiscarded: noop,

@@ -685,8 +497,6 @@ // switches

// providers
compare: compare,
isPaused: function() {
return false;
},
cache: cache,
mutate: mutate,
compare,
isPaused: ()=>false,
cache,
mutate,
fallback: {}

@@ -696,9 +506,9 @@ }, // use web preset by default

var mergeConfigs = function(a, b) {
const mergeConfigs = (a, b)=>{
// Need to create a new object to avoid mutating the original here.
var v = mergeObjects(a, b);
const 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;
const { use: u1 , fallback: f1 } = a;
const { use: u2 , fallback: f2 } = b;
if (u1 && u2) {

@@ -714,10 +524,8 @@ v.use = u1.concat(u2);

var SWRConfigContext = React.createContext({});
var SWRConfig = function(props) {
var value = props.value;
var parentConfig = React.useContext(SWRConfigContext);
var isFunctionalConfig = isFunction(value);
var config = React.useMemo(function() {
return isFunctionalConfig ? value(parentConfig) : value;
}, [
const SWRConfigContext = React.createContext({});
const SWRConfig = (props)=>{
const { value } = props;
const parentConfig = React.useContext(SWRConfigContext);
const isFunctionalConfig = isFunction(value);
const config = React.useMemo(()=>isFunctionalConfig ? value(parentConfig) : value, [
isFunctionalConfig,

@@ -728,5 +536,3 @@ parentConfig,

// Extend parent context values and middleware.
var extendedConfig = React.useMemo(function() {
return isFunctionalConfig ? config : mergeConfigs(parentConfig, config);
}, [
const extendedConfig = React.useMemo(()=>isFunctionalConfig ? config : mergeConfigs(parentConfig, config), [
isFunctionalConfig,

@@ -737,7 +543,5 @@ parentConfig,

// Should not use the inherited provider.
var provider = config && config.provider;
const provider = config && config.provider;
// Use a lazy initialized state to create the cache on first access.
var ref = React.useState(function() {
return provider ? initCache(provider(extendedConfig.cache || cache), config) : UNDEFINED;
}), cacheContext = ref[0];
const [cacheContext] = React.useState(()=>provider ? initCache(provider(extendedConfig.cache || cache), config) : UNDEFINED);
// Override the cache if a new provider is given.

@@ -749,3 +553,3 @@ if (cacheContext) {

// Unsubscribe events.
useIsomorphicLayoutEffect(function() {
useIsomorphicLayoutEffect(()=>{
if (cacheContext) {

@@ -762,5 +566,5 @@ cacheContext[2] && cacheContext[2]();

// @ts-expect-error
var enableDevtools = isWindowDefined && window.__SWR_DEVTOOLS_USE__;
var use = enableDevtools ? window.__SWR_DEVTOOLS_USE__ : [];
var setupDevTools = function() {
const enableDevtools = isWindowDefined && window.__SWR_DEVTOOLS_USE__;
const use = enableDevtools ? window.__SWR_DEVTOOLS_USE__ : [];
const setupDevTools = ()=>{
if (enableDevtools) {

@@ -772,3 +576,3 @@ // @ts-expect-error

var normalize = function(args) {
const normalize = (args)=>{
return isFunction(args[1]) ? [

@@ -785,25 +589,21 @@ args[0],

var useSWRConfig = function() {
const useSWRConfig = ()=>{
return mergeObjects(defaultConfig, React.useContext(SWRConfigContext));
};
var preload = function(key_, fetcher) {
var key = serialize(key_)[0];
var ref = SWRGlobalState.get(cache), PRELOAD = ref[3];
const preload = (key_, fetcher)=>{
const key = serialize(key_)[0];
const [, , , PRELOAD] = SWRGlobalState.get(cache);
// Prevent preload to be called multiple times before used.
if (PRELOAD[key]) return PRELOAD[key];
var req = fetcher(key_);
const req = fetcher(key_);
PRELOAD[key] = req;
return req;
};
var middleware = function(useSWRNext) {
return function(key_, fetcher_, config) {
const middleware = (useSWRNext)=>(key_, fetcher_, config)=>{
// fetcher might be a sync function, so this should not be an async function
var fetcher = fetcher_ && function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
var key = serialize(key_)[0];
var ref = SWRGlobalState.get(cache), PRELOAD = ref[3];
var req = PRELOAD[key];
const fetcher = fetcher_ && ((...args)=>{
const key = serialize(key_)[0];
const [, , , PRELOAD] = SWRGlobalState.get(cache);
const req = PRELOAD[key];
if (req) {

@@ -813,28 +613,24 @@ delete PRELOAD[key];

}
return fetcher_.apply(void 0, args);
};
return fetcher_(...args);
});
return useSWRNext(key_, fetcher, config);
};
};
var BUILT_IN_MIDDLEWARE = use.concat(middleware);
const BUILT_IN_MIDDLEWARE = use.concat(middleware);
// It's tricky to pass generic types as parameters, so we just directly override
// the types here.
var withArgs = function(hook) {
return function useSWRArgs() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
const withArgs = (hook)=>{
return function useSWRArgs(...args) {
// Get the default and inherited configuration.
var fallbackConfig = useSWRConfig();
const fallbackConfig = useSWRConfig();
// Normalize arguments.
var ref = normalize(args), key = ref[0], fn = ref[1], _config = ref[2];
const [key, fn, _config] = normalize(args);
// Merge configurations.
var config = mergeConfigs(fallbackConfig, _config);
const config = mergeConfigs(fallbackConfig, _config);
// Apply middleware
var next = hook;
var use = config.use;
var middleware = (use || []).concat(BUILT_IN_MIDDLEWARE);
for(var i = middleware.length; i--;){
let next = hook;
const { use } = config;
const middleware = (use || []).concat(BUILT_IN_MIDDLEWARE);
for(let i = middleware.length; i--;){
next = middleware[i](next);

@@ -848,6 +644,6 @@ }

* An implementation of state with dependency-tracking.
*/ var useStateWithDeps = function(state) {
var rerender = React.useState({})[1];
var unmountedRef = React.useRef(false);
var stateRef = React.useRef(state);
*/ const useStateWithDeps = (state)=>{
const rerender = React.useState({})[1];
const unmountedRef = React.useRef(false);
const stateRef = React.useRef(state);
// If a state property (data, error, or isValidating) is accessed by the render

@@ -857,3 +653,3 @@ // function, we mark the property as a dependency so if it is updated again

// This is also known as dependency-tracking.
var stateDependenciesRef = React.useRef({
const stateDependenciesRef = React.useRef({
data: false,

@@ -879,7 +675,7 @@ error: false,

* ```
*/ var setState = React.useCallback(function(payload) {
var shouldRerender = false;
var currentState = stateRef.current;
for(var _ in payload){
var k = _;
*/ const setState = React.useCallback((payload)=>{
let shouldRerender = false;
const currentState = stateRef.current;
for(const _ in payload){
const k = _;
// If the property has changed, update the state and mark rerender as

@@ -900,5 +696,3 @@ // needed.

} else {
React__default["default"].startTransition(function() {
return rerender({});
});
React__default["default"].startTransition(()=>rerender({}));
}

@@ -909,5 +703,5 @@ }

[]);
useIsomorphicLayoutEffect(function() {
useIsomorphicLayoutEffect(()=>{
unmountedRef.current = false;
return function() {
return ()=>{
unmountedRef.current = true;

@@ -925,7 +719,7 @@ };

// the unsubscribe function.
var subscribeCallback = function(key, callbacks, callback) {
var keyedRevalidators = callbacks[key] || (callbacks[key] = []);
const subscribeCallback = (key, callbacks, callback)=>{
const keyedRevalidators = callbacks[key] || (callbacks[key] = []);
keyedRevalidators.push(callback);
return function() {
var index = keyedRevalidators.indexOf(callback);
return ()=>{
const index = keyedRevalidators.indexOf(callback);
if (index >= 0) {

@@ -939,27 +733,11 @@ // O(1): faster than splice

function _extends() {
_extends = Object.assign || function(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i];
for(var key in source){
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
// Create a custom hook with a middleware
var withMiddleware = function(useSWR, middleware) {
return function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
var ref = normalize(args), key = ref[0], fn = ref[1], config = ref[2];
var uses = (config.use || []).concat(middleware);
return useSWR(key, fn, _extends({}, config, {
const withMiddleware = (useSWR, middleware)=>{
return (...args)=>{
const [key, fn, config] = normalize(args);
const uses = (config.use || []).concat(middleware);
return useSWR(key, fn, {
...config,
use: uses
}));
});
};

@@ -966,0 +744,0 @@ };

{
"main": "./dist/index.js",
"module": "./dist/index.esm.js",
"types": "./dist/_internal/index.d.ts",
"types": "./dist/index.d.ts",
"exports": "./dist/index.mjs",
"private": true,
"scripts": {
"watch": "bunchee index.ts -w",
"build": "bunchee index.ts",
"watch": "bunchee --target es2018 index.ts -w",
"build": "bunchee --target es2018 index.ts",
"types:check": "tsc --noEmit",

@@ -11,0 +11,0 @@ "clean": "rimraf dist"

import * as react from 'react';
import { FullConfiguration as FullConfiguration$1, Key as Key$1, SWRHook as SWRHook$1 } from 'swr/_internal';
import * as swr__internal from 'swr/_internal';
import { FullConfiguration, Key, SWRHook } from 'swr/_internal';
export { Arguments, BareFetcher, Cache, Fetcher, Key, KeyLoader, KeyedMutator, Middleware, MutatorCallback, MutatorOptions, Revalidator, RevalidatorOptions, SWRConfiguration, SWRHook, SWRResponse, State, mutate, preload, useSWRConfig } from 'swr/_internal';
declare const defaultConfig: FullConfiguration;
declare type FetcherResponse<Data = unknown> = Data | Promise<Data>;
declare type BareFetcher<Data = unknown> = (...args: any[]) => FetcherResponse<Data>;
declare type Fetcher<Data = unknown, SWRKey extends Key = Key> = SWRKey extends () => infer Arg | null | undefined | false ? (args: Arg) => FetcherResponse<Data> : SWRKey extends null | undefined | false ? never : SWRKey extends infer Arg ? (args: Arg) => FetcherResponse<Data> : never;
interface InternalConfiguration {
cache: Cache;
mutate: ScopedMutator;
}
/**
* @link https://swr.vercel.app/docs/options
*/
interface PublicConfiguration<Data = any, Error = any, Fn extends Fetcher = BareFetcher> {
/**
* error retry interval in milliseconds
* @defaultValue 5000
*/
errorRetryInterval: number;
/** max error retry count */
errorRetryCount?: number;
/**
* timeout to trigger the onLoadingSlow event in milliseconds
* @defaultValue 3000
*/
loadingTimeout: number;
/**
* only revalidate once during a time span in milliseconds
* @defaultValue 5000
*/
focusThrottleInterval: number;
/**
* dedupe requests with the same key in this time span in milliseconds
* @defaultValue 2000
*/
dedupingInterval: number;
/**
* @link https://swr.vercel.app/docs/revalidation
* * Disabled by default: `refreshInterval = 0`
* * If set to a number, polling interval in milliseconds
* * If set to a function, the function will receive the latest data and should return the interval in milliseconds
*/
refreshInterval?: number | ((latestData: Data | undefined) => number);
/**
* polling when the window is invisible (if `refreshInterval` is enabled)
* @defaultValue false
*
*/
refreshWhenHidden?: boolean;
/**
* polling when the browser is offline (determined by `navigator.onLine`)
*/
refreshWhenOffline?: boolean;
/**
* automatically revalidate when window gets focused
* @defaultValue true
* @link https://swr.vercel.app/docs/revalidation
*/
revalidateOnFocus: boolean;
/**
* automatically revalidate when the browser regains a network connection (via `navigator.onLine`)
* @defaultValue true
* @link https://swr.vercel.app/docs/revalidation
*/
revalidateOnReconnect: boolean;
/**
* enable or disable automatic revalidation when component is mounted
*/
revalidateOnMount?: boolean;
/**
* automatically revalidate even if there is stale data
* @defaultValue true
* @link https://swr.vercel.app/docs/revalidation#disable-automatic-revalidations
*/
revalidateIfStale: boolean;
/**
* retry when fetcher has an error
* @defaultValue true
*/
shouldRetryOnError: boolean | ((err: Error) => boolean);
/**
* keep the previous result when key is changed but data is not ready
* @defaultValue false
*/
keepPreviousData?: boolean;
/**
* @experimental enable React Suspense mode
* @defaultValue false
* @link https://swr.vercel.app/docs/suspense
*/
suspense?: boolean;
/**
* initial data to be returned (note: ***This is per-hook***)
*/
fallbackData?: Data;
/**
* the fetcher function
*/
fetcher?: Fn;
/**
* array of middleware functions
* @link https://swr.vercel.app/docs/middleware
*/
use?: Middleware[];
/**
* a key-value object of multiple fallback data
* @link https://swr.vercel.app/docs/with-nextjs#pre-rendering-with-default-data
*/
fallback: {
[key: string]: any;
};
/**
* function to detect whether pause revalidations, will ignore fetched data and errors when it returns true. Returns false by default.
*/
isPaused: () => boolean;
/**
* callback function when a request takes too long to load (see `loadingTimeout`)
*/
onLoadingSlow: (key: string, config: Readonly<PublicConfiguration<Data, Error, Fn>>) => void;
/**
* callback function when a request finishes successfully
*/
onSuccess: (data: Data, key: string, config: Readonly<PublicConfiguration<Data, Error, Fn>>) => void;
/**
* callback function when a request returns an error
*/
onError: (err: Error, key: string, config: Readonly<PublicConfiguration<Data, Error, Fn>>) => void;
/**
* handler for error retry
*/
onErrorRetry: (err: Error, key: string, config: Readonly<PublicConfiguration<Data, Error, Fn>>, revalidate: Revalidator, revalidateOpts: Required<RevalidatorOptions>) => void;
/**
* callback function when a request is ignored
*/
onDiscarded: (key: string) => void;
/**
* comparison function used to detect when returned data has changed, to avoid spurious rerenders. By default, [stable-hash](https://github.com/shuding/stable-hash) is used.
*/
compare: (a: Data | undefined, b: Data | undefined) => boolean;
/**
* isOnline and isVisible are functions that return a boolean, to determine if the application is "active". By default, SWR will bail out a revalidation if these conditions are not met.
* @link https://swr.vercel.app/docs/advanced/react-native#customize-focus-and-reconnect-events
*/
isOnline: () => boolean;
/**
* isOnline and isVisible are functions that return a boolean, to determine if the application is "active". By default, SWR will bail out a revalidation if these conditions are not met.
* @link https://swr.vercel.app/docs/advanced/react-native#customize-focus-and-reconnect-events
*/
isVisible: () => boolean;
}
declare type FullConfiguration = InternalConfiguration & PublicConfiguration;
declare type ProviderConfiguration = {
initFocus: (callback: () => void) => (() => void) | void;
initReconnect: (callback: () => void) => (() => void) | void;
};
/**
* @example
* ```ts
* const { data, error } = useSWR(key, fetcher)
* ```
*/
interface SWRHook {
<Data = any, Error = any, SWRKey extends Key = null>(key: SWRKey): SWRResponse<Data, Error>;
<Data = any, Error = any, SWRKey extends Key = null>(key: SWRKey, fetcher: Fetcher<Data, SWRKey> | null): SWRResponse<Data, Error>;
<Data = any, Error = any, SWRKey extends Key = null>(key: SWRKey, config: SWRConfiguration<Data, Error, Fetcher<Data, SWRKey>> | undefined): SWRResponse<Data, Error>;
<Data = any, Error = any, SWRKey extends Key = null>(key: SWRKey, fetcher: Fetcher<Data, SWRKey> | null, config: SWRConfiguration<Data, Error, Fetcher<Data, SWRKey>> | undefined): SWRResponse<Data, Error>;
<Data = any, Error = any>(key: Key): SWRResponse<Data, Error>;
<Data = any, Error = any>(key: Key, fetcher: BareFetcher<Data> | null): SWRResponse<Data, Error>;
<Data = any, Error = any>(key: Key, config: SWRConfiguration<Data, Error, BareFetcher<Data>> | undefined): SWRResponse<Data, Error>;
<Data = any, Error = any>(key: Key, fetcher: BareFetcher<Data> | null, config: SWRConfiguration<Data, Error, BareFetcher<Data>> | undefined): SWRResponse<Data, Error>;
}
declare type Middleware = (useSWRNext: SWRHook) => <Data = any, Error = any>(key: Key, fetcher: BareFetcher<Data> | null, config: typeof defaultConfig & SWRConfiguration<Data, Error, BareFetcher<Data>>) => SWRResponse<Data, Error>;
declare type ArgumentsTuple = [any, ...unknown[]] | readonly [any, ...unknown[]];
declare type Arguments = string | ArgumentsTuple | Record<any, any> | null | undefined | false;
declare type Key = Arguments | (() => Arguments);
declare type MutatorCallback<Data = any> = (currentData?: Data) => Promise<undefined | Data> | undefined | Data;
declare type MutatorOptions<Data = any> = {
revalidate?: boolean;
populateCache?: boolean | ((result: any, currentData: Data | undefined) => Data);
optimisticData?: Data | ((currentData?: Data) => Data);
rollbackOnError?: boolean;
throwOnError?: boolean;
};
declare type State<Data = any, Error = any> = {
data?: Data;
error?: Error;
isValidating?: boolean;
isLoading?: boolean;
};
interface ScopedMutator<Data = any> {
<T = Data>(matcher: (key?: Arguments) => boolean, data?: T | Promise<T> | MutatorCallback<T>, opts?: boolean | MutatorOptions<Data>): Promise<Array<T | undefined>>;
<T = Data>(key: Arguments, data?: T | Promise<T> | MutatorCallback<T>, opts?: boolean | MutatorOptions<Data>): Promise<T | undefined>;
}
declare type KeyedMutator<Data> = (data?: Data | Promise<Data> | MutatorCallback<Data>, opts?: boolean | MutatorOptions<Data>) => Promise<Data | undefined>;
declare type SWRConfiguration<Data = any, Error = any, Fn extends BareFetcher<any> = BareFetcher<any>> = Partial<PublicConfiguration<Data, Error, Fn>>;
interface SWRResponse<Data = any, Error = any> {
/**
* The returned data of the fetcher function.
*/
data: Data | undefined;
/**
* The error object thrown by the fetcher function.
*/
error: Error | undefined;
mutate: KeyedMutator<Data>;
isValidating: boolean;
isLoading: boolean;
}
interface RevalidatorOptions {
retryCount?: number;
dedupe?: boolean;
}
declare type Revalidator = (revalidateOpts?: RevalidatorOptions) => Promise<boolean> | void;
interface Cache<Data = any> {
keys(): IterableIterator<string>;
get(key: Key): State<Data> | undefined;
set(key: Key, value: State<Data>): void;
delete(key: Key): void;
}
declare const SWRConfig: react.FC<react.PropsWithChildren<{
value?: (Partial<PublicConfiguration<any, any, BareFetcher<any>>> & Partial<ProviderConfiguration> & {
provider?: ((cache: Readonly<Cache<any>>) => Cache<any>) | undefined;
}) | ((parentConfig?: (Partial<PublicConfiguration<any, any, BareFetcher<any>>> & Partial<ProviderConfiguration> & {
provider?: ((cache: Readonly<Cache<any>>) => Cache<any>) | undefined;
}) | undefined) => Partial<PublicConfiguration<any, any, BareFetcher<any>>> & Partial<ProviderConfiguration> & {
provider?: ((cache: Readonly<Cache<any>>) => Cache<any>) | undefined;
value?: (Partial<swr__internal.PublicConfiguration<any, any, swr__internal.BareFetcher<any>>> & Partial<swr__internal.ProviderConfiguration> & {
provider?: ((cache: Readonly<swr__internal.Cache<any>>) => swr__internal.Cache<any>) | undefined;
}) | ((parentConfig?: (Partial<swr__internal.PublicConfiguration<any, any, swr__internal.BareFetcher<any>>> & Partial<swr__internal.ProviderConfiguration> & {
provider?: ((cache: Readonly<swr__internal.Cache<any>>) => swr__internal.Cache<any>) | undefined;
}) | undefined) => Partial<swr__internal.PublicConfiguration<any, any, swr__internal.BareFetcher<any>>> & Partial<swr__internal.ProviderConfiguration> & {
provider?: ((cache: Readonly<swr__internal.Cache<any>>) => swr__internal.Cache<any>) | undefined;
}) | undefined;
}>> & {
defaultValue: FullConfiguration$1;
defaultValue: FullConfiguration;
};
declare const unstable_serialize: (key: Key$1) => string;
declare const unstable_serialize: (key: Key) => string;
/**

@@ -251,4 +33,4 @@ * A hook to fetch data.

*/
declare const _default: SWRHook$1;
declare const _default: SWRHook;
export { SWRConfig, _default as default, unstable_serialize };
import { useRef, useMemo, useCallback, useDebugValue } from 'react';
import { useSyncExternalStore } from 'use-sync-external-store/shim/index.js';
import { OBJECT, SWRConfig as SWRConfig$1, defaultConfig, withArgs, SWRGlobalState, serialize, createCacheHelper, isUndefined, internalMutate, useIsomorphicLayoutEffect, UNDEFINED, subscribeCallback, IS_SERVER, rAF, IS_REACT_LEGACY, mergeObjects, revalidateEvents, isFunction, getTimestamp } from 'swr/_internal';
import { OBJECT, SWRConfig as SWRConfig$1, defaultConfig, withArgs, SWRGlobalState, serialize, createCacheHelper, isUndefined, getTimestamp, UNDEFINED, isFunction, internalMutate, useIsomorphicLayoutEffect, subscribeCallback, IS_SERVER, rAF, IS_REACT_LEGACY, mergeObjects, revalidateEvents } from 'swr/_internal';
export { mutate, preload, useSWRConfig } from 'swr/_internal';
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
var __generator = undefined && undefined.__generator || function(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
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 WITH_DEDUPE = {
const WITH_DEDUPE = {
dedupe: true
};
var useSWRHandler = function(_key, fetcher, config) {
var cache = config.cache, compare = config.compare, suspense = config.suspense, fallbackData = config.fallbackData, revalidateOnMount = config.revalidateOnMount, refreshInterval = config.refreshInterval, refreshWhenHidden = config.refreshWhenHidden, refreshWhenOffline = config.refreshWhenOffline, keepPreviousData = config.keepPreviousData;
var ref = SWRGlobalState.get(cache), EVENT_REVALIDATORS = ref[0], MUTATION = ref[1], FETCH = ref[2];
const useSWRHandler = (_key, fetcher, config)=>{
const { cache , compare , suspense , fallbackData , revalidateOnMount , refreshInterval , refreshWhenHidden , refreshWhenOffline , keepPreviousData } = config;
const [EVENT_REVALIDATORS, MUTATION, FETCH] = SWRGlobalState.get(cache);
// `key` is the identifier of the SWR `data` state, `keyInfo` holds extra

@@ -166,28 +17,24 @@ // states such as `error` and `isValidating` inside,

// to the fetcher.
var ref1 = serialize(_key), key = ref1[0], fnArg = ref1[1];
const [key, fnArg] = serialize(_key);
// If it's the initial render of this hook.
var initialMountedRef = useRef(false);
const 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);
const 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 ref2 = createCacheHelper(cache, key), getCache = ref2[0], setCache = ref2[1], subscribeCache = ref2[2];
var stateDependencies = useRef({}).current;
const keyRef = useRef(key);
const fetcherRef = useRef(fetcher);
const configRef = useRef(config);
const getConfig = ()=>configRef.current;
const isActive = ()=>getConfig().isVisible() && getConfig().isOnline();
const [getCache, setCache, subscribeCache] = createCacheHelper(cache, key);
const stateDependencies = useRef({}).current;
// eslint-disable-next-line react-hooks/exhaustive-deps
var fallback = isUndefined(fallbackData) ? config.fallback[key] : fallbackData;
var isEqual = function(prev, current) {
var equal = true;
for(var _ in stateDependencies){
var t = _;
const fallback = isUndefined(fallbackData) ? config.fallback[key] : fallbackData;
const isEqual = (prev, current)=>{
let equal = true;
for(const _ in stateDependencies){
const t = _;
if (!compare(current[t], prev[t])) {
if (t === "data" && isUndefined(prev[t])) {
if (t === 'data' && isUndefined(prev[t])) {
if (!compare(current[t], returnedData)) {

@@ -203,4 +50,4 @@ equal = false;

};
var getSnapshot = useMemo(function() {
var shouldStartRequest = function() {
const getSnapshot = useMemo(()=>{
const shouldStartRequest = (()=>{
if (!key) return false;

@@ -214,7 +61,7 @@ if (!fetcher) return false;

return true;
}();
var getSelectedCache = function() {
var state = getCache();
})();
const getSelectedCache = ()=>{
const state = getCache();
// We only select the needed fields from the state.
var snapshot = mergeObjects(state);
const snapshot = mergeObjects(state);
delete snapshot._k;

@@ -224,10 +71,11 @@ if (!shouldStartRequest) {

}
return Object.assign({
return {
isValidating: true,
isLoading: true
}, snapshot);
isLoading: true,
...snapshot
};
};
var memorizedSnapshot = getSelectedCache();
return function() {
var snapshot = getSelectedCache();
let memorizedSnapshot = getSelectedCache();
return ()=>{
const snapshot = getSelectedCache();
return isEqual(snapshot, memorizedSnapshot) ? memorizedSnapshot : memorizedSnapshot = snapshot;

@@ -241,7 +89,5 @@ };

// Get the current state that SWR should return.
var cached = useSyncExternalStore(useCallback(function(callback) {
return subscribeCache(key, function(prev, current) {
const cached = useSyncExternalStore(useCallback((callback)=>subscribeCache(key, (prev, current)=>{
if (!isEqual(prev, current)) callback();
});
}, // eslint-disable-next-line react-hooks/exhaustive-deps
}), // eslint-disable-next-line react-hooks/exhaustive-deps
[

@@ -251,13 +97,13 @@ cache,

]), getSnapshot, getSnapshot);
var isInitialMount = !initialMountedRef.current;
var cachedData = cached.data;
var data = isUndefined(cachedData) ? fallback : cachedData;
var error = cached.error;
const isInitialMount = !initialMountedRef.current;
const cachedData = cached.data;
const data = isUndefined(cachedData) ? fallback : cachedData;
const error = cached.error;
// Use a ref to store previously returned data. Use the initial data as its initial value.
var laggyDataRef = useRef(data);
var returnedData = keepPreviousData ? isUndefined(cachedData) ? laggyDataRef.current : cachedData : data;
const laggyDataRef = useRef(data);
const returnedData = keepPreviousData ? isUndefined(cachedData) ? laggyDataRef.current : cachedData : data;
// - 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 shouldDoInitialRevalidation = function() {
const shouldDoInitialRevalidation = (()=>{
// If `revalidateOnMount` is set, we take the value directly.

@@ -274,178 +120,173 @@ if (isInitialMount && !isUndefined(revalidateOnMount)) return revalidateOnMount;

return isUndefined(data) || config.revalidateIfStale;
}();
})();
// Resolve the default validating state:
// If it's able to validate, and it should revalidate when mount, this will be true.
var defaultValidatingState = !!(key && fetcher && isInitialMount && shouldDoInitialRevalidation);
var isValidating = isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating;
var isLoading = isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading;
const defaultValidatingState = !!(key && fetcher && isInitialMount && shouldDoInitialRevalidation);
const isValidating = isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating;
const isLoading = isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading;
// The revalidation function is a carefully crafted wrapper of the original
// `fetcher`, to correctly handle the many edge cases.
var revalidate = useCallback(/*#__PURE__*/ _asyncToGenerator(function(revalidateOpts) {
var currentFetcher, newData, startAt, loading, opts, _tmp, shouldStartNewRequest, callbackSafeguard, finalState, _tmp1, finishRequestAndUpdateState, cleanupState, initialState, _tmp2, ref, mutationInfo, cacheData, err, currentConfig, shouldRetryOnError, _tmp3;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
currentFetcher = fetcherRef.current;
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) {
return [
2,
false
];
}
loading = true;
_tmp = {};
opts = revalidateOpts || _tmp;
shouldStartNewRequest = !FETCH[key] || !opts.dedupe;
callbackSafeguard = function() {
if (IS_REACT_LEGACY) {
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;
const revalidate = useCallback(async (revalidateOpts)=>{
const currentFetcher = fetcherRef.current;
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) {
return false;
}
let newData;
let startAt;
let loading = true;
const opts = revalidateOpts || {};
// If there is no ongoing concurrent request, or `dedupe` is not set, a
// new request should be initiated.
const shouldStartNewRequest = !FETCH[key] || !opts.dedupe;
/*
For React 17
Do unmount check for calls:
If key has changed during the revalidation, or the component has been
unmounted, old dispatch and old event callbacks should not take any
effect
For React 18
only check if key has changed
https://github.com/reactwg/react-18/discussions/82
*/ const callbackSafeguard = ()=>{
if (IS_REACT_LEGACY) {
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;
}
return key === keyRef.current;
};
// The final state object when the request finishes.
const finalState = {
isValidating: false,
isLoading: false
};
const finishRequestAndUpdateState = ()=>{
setCache(finalState);
};
const cleanupState = ()=>{
// Check if it's still the same request before deleting it.
const requestInfo = FETCH[key];
if (requestInfo && requestInfo[1] === startAt) {
delete FETCH[key];
}
};
// Start fetching. Change the `isValidating` state, update the cache.
const initialState = {
isValidating: true
};
// It is in the `isLoading` state, if and only if there is no cached data.
// This bypasses fallback data and laggy data.
if (isUndefined(getCache().data)) {
initialState.isLoading = true;
}
try {
if (shouldStartNewRequest) {
setCache(initialState);
// If no cache is being rendered currently (it shows a blank page),
// we trigger the loading slow event.
if (config.loadingTimeout && isUndefined(getCache().data)) {
setTimeout(()=>{
if (loading && callbackSafeguard()) {
getConfig().onLoadingSlow(key, config);
}
return key === keyRef.current;
};
_tmp1 = {};
finalState = (_tmp1.isValidating = false, _tmp1.isLoading = false, _tmp1);
finishRequestAndUpdateState = function() {
setCache(finalState);
};
cleanupState = function() {
// Check if it's still the same request before deleting it.
var requestInfo = FETCH[key];
if (requestInfo && requestInfo[1] === startAt) {
delete FETCH[key];
}
};
_tmp2 = {};
initialState = (_tmp2.isValidating = true, _tmp2);
// It is in the `isLoading` state, if and only if there is no cached data.
// This bypasses fallback data and laggy data.
if (isUndefined(getCache().data)) {
initialState.isLoading = true;
}, config.loadingTimeout);
}
// Start the request and save the timestamp.
// Key must be truthy if entering here.
FETCH[key] = [
currentFetcher(fnArg),
getTimestamp()
];
}
[newData, startAt] = FETCH[key];
newData = await newData;
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 (callbackSafeguard()) {
getConfig().onDiscarded(key);
}
_state.label = 1;
case 1:
_state.trys.push([
1,
3,
,
4
]);
if (shouldStartNewRequest) {
setCache(initialState);
// If no cache is being rendered currently (it shows a blank page),
// we trigger the loading slow event.
if (config.loadingTimeout && isUndefined(getCache().data)) {
setTimeout(function() {
if (loading && callbackSafeguard()) {
getConfig().onLoadingSlow(key, config);
}
}, config.loadingTimeout);
}
// Start the request and save the timestamp.
// Key must be truthy if entering here.
FETCH[key] = [
currentFetcher(fnArg),
getTimestamp()
];
}
return false;
}
// Clear error.
finalState.error = UNDEFINED;
// If there're other mutations(s), that overlapped with the current revalidation:
// case 1:
// req------------------>res
// mutate------>end
// case 2:
// req------------>res
// mutate------>end
// case 3:
// req------------------>res
// mutate-------...---------->
// we have to ignore the revalidation result (res) because it's no longer fresh.
// meanwhile, a new revalidation should be triggered when the mutation ends.
const 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 (callbackSafeguard()) {
getConfig().onDiscarded(key);
}
ref = FETCH[key], newData = ref[0], startAt = ref[1];
return [
4,
newData
];
case 2:
newData = _state.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 (callbackSafeguard()) {
getConfig().onDiscarded(key);
}
}
return false;
}
// Deep compare with the latest state to avoid extra re-renders.
// For local state, compare and assign.
const cacheData = getCache().data;
// Since the compare fn could be custom fn
// cacheData might be different from newData even when compare fn returns True
finalState.data = compare(cacheData, newData) ? cacheData : newData;
// Trigger the successful callback if it's the original request.
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onSuccess(newData, key, config);
}
}
} catch (err) {
cleanupState();
const currentConfig = getConfig();
const { shouldRetryOnError } = currentConfig;
// Not paused, we continue handling the error. Otherwise, discard it.
if (!currentConfig.isPaused()) {
// Get a new error, don't use deep comparison for errors.
finalState.error = err;
// Error event and retry logic. Only for the actual request, not
// deduped ones.
if (shouldStartNewRequest && callbackSafeguard()) {
currentConfig.onError(err, key, currentConfig);
if (shouldRetryOnError === true || isFunction(shouldRetryOnError) && shouldRetryOnError(err)) {
if (isActive()) {
// If it's inactive, stop. It will auto-revalidate when
// refocusing or reconnecting.
// When retrying, deduplication is always enabled.
currentConfig.onErrorRetry(err, key, currentConfig, revalidate, {
retryCount: (opts.retryCount || 0) + 1,
dedupe: true
});
}
return [
2,
false
];
}
// Clear error.
finalState.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 (callbackSafeguard()) {
getConfig().onDiscarded(key);
}
}
return [
2,
false
];
}
cacheData = getCache().data;
// Since the compare fn could be custom fn
// cacheData might be different from newData even when compare fn returns True
finalState.data = compare(cacheData, newData) ? cacheData : newData;
// Trigger the successful callback if it's the original request.
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onSuccess(newData, key, config);
}
}
return [
3,
4
];
case 3:
err = _state.sent();
cleanupState();
currentConfig = getConfig();
shouldRetryOnError = currentConfig.shouldRetryOnError;
_tmp3 = {};
// Not paused, we continue handling the error. Otherwise, discard it.
if (!currentConfig.isPaused()) {
// Get a new error, don't use deep comparison for errors.
finalState.error = err;
// Error event and retry logic. Only for the actual request, not
// deduped ones.
if (shouldStartNewRequest && callbackSafeguard()) {
currentConfig.onError(err, key, currentConfig);
if (shouldRetryOnError === true || isFunction(shouldRetryOnError) && shouldRetryOnError(err)) {
if (isActive()) {
// If it's inactive, stop. It will auto-revalidate when
// refocusing or reconnecting.
// When retrying, deduplication is always enabled.
currentConfig.onErrorRetry(err, key, currentConfig, revalidate, (_tmp3.retryCount = (opts.retryCount || 0) + 1, _tmp3.dedupe = true, _tmp3));
}
}
}
}
return [
3,
4
];
case 4:
// Mark loading as stopped.
loading = false;
// Update the current hook's state.
finishRequestAndUpdateState();
return [
2,
true
];
}
}
});
}), // `setState` is immutable, and `eventsCallback`, `fnArg`, and
}
// Mark loading as stopped.
loading = false;
// Update the current hook's state.
finishRequestAndUpdateState();
return true;
}, // `setState` is immutable, and `eventsCallback`, `fnArg`, and
// `keyValidating` are depending on `key`, so we can exclude them from

@@ -468,15 +309,9 @@ // the deps array.

// eslint-disable-next-line react-hooks/exhaustive-deps
var boundMutate = useCallback(// Use callback to make sure `keyRef.current` returns latest result every time
function() {
for(var _len = arguments.length, args = new Array(_len), _$_key = 0; _$_key < _len; _$_key++){
args[_$_key] = arguments[_$_key];
}
return internalMutate.apply(void 0, [
cache,
keyRef.current
].concat(_toConsumableArray(args)));
const boundMutate = useCallback(// Use callback to make sure `keyRef.current` returns latest result every time
(...args)=>{
return internalMutate(cache, keyRef.current, ...args);
}, // eslint-disable-next-line react-hooks/exhaustive-deps
[]);
// The logic for updating refs.
useIsomorphicLayoutEffect(function() {
useIsomorphicLayoutEffect(()=>{
fetcherRef.current = fetcher;

@@ -491,11 +326,11 @@ configRef.current = config;

// After mounted or key changed.
useIsomorphicLayoutEffect(function() {
useIsomorphicLayoutEffect(()=>{
if (!key) return;
var softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE);
const softRevalidate = revalidate.bind(UNDEFINED, WITH_DEDUPE);
// Expose revalidators to global event listeners. So we can trigger
// revalidation from the outside.
var nextFocusRevalidatedAt = 0;
var onRevalidate = function(type) {
let nextFocusRevalidatedAt = 0;
const onRevalidate = (type)=>{
if (type == revalidateEvents.FOCUS_EVENT) {
var now = Date.now();
const now = Date.now();
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) {

@@ -514,3 +349,3 @@ nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval;

};
var unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);
const unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);
// Mark the component as mounted and update corresponding refs.

@@ -535,3 +370,3 @@ unmountedRef.current = false;

}
return function() {
return ()=>{
// Mark it as unmounted.

@@ -545,7 +380,8 @@ unmountedRef.current = true;

// Polling
useIsomorphicLayoutEffect(function() {
var next = function next() {
useIsomorphicLayoutEffect(()=>{
let 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;
const interval = isFunction(refreshInterval) ? refreshInterval(data) : refreshInterval;
// We only start the next interval if `refreshInterval` is not 0, and:

@@ -557,4 +393,4 @@ // - `force` is true, which is the start of polling

}
};
var execute = function execute() {
}
function execute() {
// Check if it's OK to execute:

@@ -568,6 +404,5 @@ // Only revalidate when the page is visible, online, and not errored.

}
};
var timer;
}
next();
return function() {
return ()=>{
if (timer) {

@@ -595,3 +430,3 @@ clearTimeout(timer);

if (!IS_REACT_LEGACY && IS_SERVER) {
throw new Error("Fallback data is required when using suspense in SSR.");
throw new Error('Fallback data is required when using suspense in SSR.');
}

@@ -624,8 +459,6 @@ // Always update fetcher and config refs even with the Suspense mode.

};
var SWRConfig = OBJECT.defineProperty(SWRConfig$1, "defaultValue", {
const SWRConfig = OBJECT.defineProperty(SWRConfig$1, 'defaultValue', {
value: defaultConfig
});
var unstable_serialize = function(key) {
return serialize(key)[0];
};
const unstable_serialize = (key)=>serialize(key)[0];
/**

@@ -632,0 +465,0 @@ * A hook to fetch data.

@@ -1,3 +0,1 @@

Object.defineProperty(exports, '__esModule', { value: true });
var react = require('react');

@@ -7,157 +5,8 @@ var index_js = require('use-sync-external-store/shim/index.js');

function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
var __generator = undefined && undefined.__generator || function(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
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 WITH_DEDUPE = {
const WITH_DEDUPE = {
dedupe: true
};
var useSWRHandler = function(_key, fetcher, config) {
var cache = config.cache, compare = config.compare, suspense = config.suspense, fallbackData = config.fallbackData, revalidateOnMount = config.revalidateOnMount, refreshInterval = config.refreshInterval, refreshWhenHidden = config.refreshWhenHidden, refreshWhenOffline = config.refreshWhenOffline, keepPreviousData = config.keepPreviousData;
var ref = _internal.SWRGlobalState.get(cache), EVENT_REVALIDATORS = ref[0], MUTATION = ref[1], FETCH = ref[2];
const useSWRHandler = (_key, fetcher, config)=>{
const { cache , compare , suspense , fallbackData , revalidateOnMount , refreshInterval , refreshWhenHidden , refreshWhenOffline , keepPreviousData } = config;
const [EVENT_REVALIDATORS, MUTATION, FETCH] = _internal.SWRGlobalState.get(cache);
// `key` is the identifier of the SWR `data` state, `keyInfo` holds extra

@@ -168,28 +17,24 @@ // states such as `error` and `isValidating` inside,

// to the fetcher.
var ref1 = _internal.serialize(_key), key = ref1[0], fnArg = ref1[1];
const [key, fnArg] = _internal.serialize(_key);
// If it's the initial render of this hook.
var initialMountedRef = react.useRef(false);
const initialMountedRef = react.useRef(false);
// If the hook is unmounted already. This will be used to prevent some effects
// to be called after unmounting.
var unmountedRef = react.useRef(false);
const unmountedRef = react.useRef(false);
// Refs to keep the key and config.
var keyRef = react.useRef(key);
var fetcherRef = react.useRef(fetcher);
var configRef = react.useRef(config);
var getConfig = function() {
return configRef.current;
};
var isActive = function() {
return getConfig().isVisible() && getConfig().isOnline();
};
var ref2 = _internal.createCacheHelper(cache, key), getCache = ref2[0], setCache = ref2[1], subscribeCache = ref2[2];
var stateDependencies = react.useRef({}).current;
const keyRef = react.useRef(key);
const fetcherRef = react.useRef(fetcher);
const configRef = react.useRef(config);
const getConfig = ()=>configRef.current;
const isActive = ()=>getConfig().isVisible() && getConfig().isOnline();
const [getCache, setCache, subscribeCache] = _internal.createCacheHelper(cache, key);
const stateDependencies = react.useRef({}).current;
// eslint-disable-next-line react-hooks/exhaustive-deps
var fallback = _internal.isUndefined(fallbackData) ? config.fallback[key] : fallbackData;
var isEqual = function(prev, current) {
var equal = true;
for(var _ in stateDependencies){
var t = _;
const fallback = _internal.isUndefined(fallbackData) ? config.fallback[key] : fallbackData;
const isEqual = (prev, current)=>{
let equal = true;
for(const _ in stateDependencies){
const t = _;
if (!compare(current[t], prev[t])) {
if (t === "data" && _internal.isUndefined(prev[t])) {
if (t === 'data' && _internal.isUndefined(prev[t])) {
if (!compare(current[t], returnedData)) {

@@ -205,4 +50,4 @@ equal = false;

};
var getSnapshot = react.useMemo(function() {
var shouldStartRequest = function() {
const getSnapshot = react.useMemo(()=>{
const shouldStartRequest = (()=>{
if (!key) return false;

@@ -216,7 +61,7 @@ if (!fetcher) return false;

return true;
}();
var getSelectedCache = function() {
var state = getCache();
})();
const getSelectedCache = ()=>{
const state = getCache();
// We only select the needed fields from the state.
var snapshot = _internal.mergeObjects(state);
const snapshot = _internal.mergeObjects(state);
delete snapshot._k;

@@ -226,10 +71,11 @@ if (!shouldStartRequest) {

}
return Object.assign({
return {
isValidating: true,
isLoading: true
}, snapshot);
isLoading: true,
...snapshot
};
};
var memorizedSnapshot = getSelectedCache();
return function() {
var snapshot = getSelectedCache();
let memorizedSnapshot = getSelectedCache();
return ()=>{
const snapshot = getSelectedCache();
return isEqual(snapshot, memorizedSnapshot) ? memorizedSnapshot : memorizedSnapshot = snapshot;

@@ -243,7 +89,5 @@ };

// Get the current state that SWR should return.
var cached = index_js.useSyncExternalStore(react.useCallback(function(callback) {
return subscribeCache(key, function(prev, current) {
const cached = index_js.useSyncExternalStore(react.useCallback((callback)=>subscribeCache(key, (prev, current)=>{
if (!isEqual(prev, current)) callback();
});
}, // eslint-disable-next-line react-hooks/exhaustive-deps
}), // eslint-disable-next-line react-hooks/exhaustive-deps
[

@@ -253,13 +97,13 @@ cache,

]), getSnapshot, getSnapshot);
var isInitialMount = !initialMountedRef.current;
var cachedData = cached.data;
var data = _internal.isUndefined(cachedData) ? fallback : cachedData;
var error = cached.error;
const isInitialMount = !initialMountedRef.current;
const cachedData = cached.data;
const data = _internal.isUndefined(cachedData) ? fallback : cachedData;
const error = cached.error;
// Use a ref to store previously returned data. Use the initial data as its initial value.
var laggyDataRef = react.useRef(data);
var returnedData = keepPreviousData ? _internal.isUndefined(cachedData) ? laggyDataRef.current : cachedData : data;
const laggyDataRef = react.useRef(data);
const returnedData = keepPreviousData ? _internal.isUndefined(cachedData) ? laggyDataRef.current : cachedData : data;
// - 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 shouldDoInitialRevalidation = function() {
const shouldDoInitialRevalidation = (()=>{
// If `revalidateOnMount` is set, we take the value directly.

@@ -276,178 +120,173 @@ if (isInitialMount && !_internal.isUndefined(revalidateOnMount)) return revalidateOnMount;

return _internal.isUndefined(data) || config.revalidateIfStale;
}();
})();
// Resolve the default validating state:
// If it's able to validate, and it should revalidate when mount, this will be true.
var defaultValidatingState = !!(key && fetcher && isInitialMount && shouldDoInitialRevalidation);
var isValidating = _internal.isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating;
var isLoading = _internal.isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading;
const defaultValidatingState = !!(key && fetcher && isInitialMount && shouldDoInitialRevalidation);
const isValidating = _internal.isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating;
const isLoading = _internal.isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading;
// The revalidation function is a carefully crafted wrapper of the original
// `fetcher`, to correctly handle the many edge cases.
var revalidate = react.useCallback(/*#__PURE__*/ _asyncToGenerator(function(revalidateOpts) {
var currentFetcher, newData, startAt, loading, opts, _tmp, shouldStartNewRequest, callbackSafeguard, finalState, _tmp1, finishRequestAndUpdateState, cleanupState, initialState, _tmp2, ref, mutationInfo, cacheData, err, currentConfig, shouldRetryOnError, _tmp3;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
currentFetcher = fetcherRef.current;
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) {
return [
2,
false
];
}
loading = true;
_tmp = {};
opts = revalidateOpts || _tmp;
shouldStartNewRequest = !FETCH[key] || !opts.dedupe;
callbackSafeguard = function() {
if (_internal.IS_REACT_LEGACY) {
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;
const revalidate = react.useCallback(async (revalidateOpts)=>{
const currentFetcher = fetcherRef.current;
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) {
return false;
}
let newData;
let startAt;
let loading = true;
const opts = revalidateOpts || {};
// If there is no ongoing concurrent request, or `dedupe` is not set, a
// new request should be initiated.
const shouldStartNewRequest = !FETCH[key] || !opts.dedupe;
/*
For React 17
Do unmount check for calls:
If key has changed during the revalidation, or the component has been
unmounted, old dispatch and old event callbacks should not take any
effect
For React 18
only check if key has changed
https://github.com/reactwg/react-18/discussions/82
*/ const callbackSafeguard = ()=>{
if (_internal.IS_REACT_LEGACY) {
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;
}
return key === keyRef.current;
};
// The final state object when the request finishes.
const finalState = {
isValidating: false,
isLoading: false
};
const finishRequestAndUpdateState = ()=>{
setCache(finalState);
};
const cleanupState = ()=>{
// Check if it's still the same request before deleting it.
const requestInfo = FETCH[key];
if (requestInfo && requestInfo[1] === startAt) {
delete FETCH[key];
}
};
// Start fetching. Change the `isValidating` state, update the cache.
const initialState = {
isValidating: true
};
// It is in the `isLoading` state, if and only if there is no cached data.
// This bypasses fallback data and laggy data.
if (_internal.isUndefined(getCache().data)) {
initialState.isLoading = true;
}
try {
if (shouldStartNewRequest) {
setCache(initialState);
// If no cache is being rendered currently (it shows a blank page),
// we trigger the loading slow event.
if (config.loadingTimeout && _internal.isUndefined(getCache().data)) {
setTimeout(()=>{
if (loading && callbackSafeguard()) {
getConfig().onLoadingSlow(key, config);
}
return key === keyRef.current;
};
_tmp1 = {};
finalState = (_tmp1.isValidating = false, _tmp1.isLoading = false, _tmp1);
finishRequestAndUpdateState = function() {
setCache(finalState);
};
cleanupState = function() {
// Check if it's still the same request before deleting it.
var requestInfo = FETCH[key];
if (requestInfo && requestInfo[1] === startAt) {
delete FETCH[key];
}
};
_tmp2 = {};
initialState = (_tmp2.isValidating = true, _tmp2);
// It is in the `isLoading` state, if and only if there is no cached data.
// This bypasses fallback data and laggy data.
if (_internal.isUndefined(getCache().data)) {
initialState.isLoading = true;
}, config.loadingTimeout);
}
// Start the request and save the timestamp.
// Key must be truthy if entering here.
FETCH[key] = [
currentFetcher(fnArg),
_internal.getTimestamp()
];
}
[newData, startAt] = FETCH[key];
newData = await newData;
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 (callbackSafeguard()) {
getConfig().onDiscarded(key);
}
_state.label = 1;
case 1:
_state.trys.push([
1,
3,
,
4
]);
if (shouldStartNewRequest) {
setCache(initialState);
// If no cache is being rendered currently (it shows a blank page),
// we trigger the loading slow event.
if (config.loadingTimeout && _internal.isUndefined(getCache().data)) {
setTimeout(function() {
if (loading && callbackSafeguard()) {
getConfig().onLoadingSlow(key, config);
}
}, config.loadingTimeout);
}
// Start the request and save the timestamp.
// Key must be truthy if entering here.
FETCH[key] = [
currentFetcher(fnArg),
_internal.getTimestamp()
];
}
return false;
}
// Clear error.
finalState.error = _internal.UNDEFINED;
// If there're other mutations(s), that overlapped with the current revalidation:
// case 1:
// req------------------>res
// mutate------>end
// case 2:
// req------------>res
// mutate------>end
// case 3:
// req------------------>res
// mutate-------...---------->
// we have to ignore the revalidation result (res) because it's no longer fresh.
// meanwhile, a new revalidation should be triggered when the mutation ends.
const mutationInfo = MUTATION[key];
if (!_internal.isUndefined(mutationInfo) && // case 1
(startAt <= mutationInfo[0] || // case 2
startAt <= mutationInfo[1] || // case 3
mutationInfo[1] === 0)) {
finishRequestAndUpdateState();
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onDiscarded(key);
}
ref = FETCH[key], newData = ref[0], startAt = ref[1];
return [
4,
newData
];
case 2:
newData = _state.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 (callbackSafeguard()) {
getConfig().onDiscarded(key);
}
}
return false;
}
// Deep compare with the latest state to avoid extra re-renders.
// For local state, compare and assign.
const cacheData = getCache().data;
// Since the compare fn could be custom fn
// cacheData might be different from newData even when compare fn returns True
finalState.data = compare(cacheData, newData) ? cacheData : newData;
// Trigger the successful callback if it's the original request.
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onSuccess(newData, key, config);
}
}
} catch (err) {
cleanupState();
const currentConfig = getConfig();
const { shouldRetryOnError } = currentConfig;
// Not paused, we continue handling the error. Otherwise, discard it.
if (!currentConfig.isPaused()) {
// Get a new error, don't use deep comparison for errors.
finalState.error = err;
// Error event and retry logic. Only for the actual request, not
// deduped ones.
if (shouldStartNewRequest && callbackSafeguard()) {
currentConfig.onError(err, key, currentConfig);
if (shouldRetryOnError === true || _internal.isFunction(shouldRetryOnError) && shouldRetryOnError(err)) {
if (isActive()) {
// If it's inactive, stop. It will auto-revalidate when
// refocusing or reconnecting.
// When retrying, deduplication is always enabled.
currentConfig.onErrorRetry(err, key, currentConfig, revalidate, {
retryCount: (opts.retryCount || 0) + 1,
dedupe: true
});
}
return [
2,
false
];
}
// Clear error.
finalState.error = _internal.UNDEFINED;
mutationInfo = MUTATION[key];
if (!_internal.isUndefined(mutationInfo) && // case 1
(startAt <= mutationInfo[0] || // case 2
startAt <= mutationInfo[1] || // case 3
mutationInfo[1] === 0)) {
finishRequestAndUpdateState();
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onDiscarded(key);
}
}
return [
2,
false
];
}
cacheData = getCache().data;
// Since the compare fn could be custom fn
// cacheData might be different from newData even when compare fn returns True
finalState.data = compare(cacheData, newData) ? cacheData : newData;
// Trigger the successful callback if it's the original request.
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onSuccess(newData, key, config);
}
}
return [
3,
4
];
case 3:
err = _state.sent();
cleanupState();
currentConfig = getConfig();
shouldRetryOnError = currentConfig.shouldRetryOnError;
_tmp3 = {};
// Not paused, we continue handling the error. Otherwise, discard it.
if (!currentConfig.isPaused()) {
// Get a new error, don't use deep comparison for errors.
finalState.error = err;
// Error event and retry logic. Only for the actual request, not
// deduped ones.
if (shouldStartNewRequest && callbackSafeguard()) {
currentConfig.onError(err, key, currentConfig);
if (shouldRetryOnError === true || _internal.isFunction(shouldRetryOnError) && shouldRetryOnError(err)) {
if (isActive()) {
// If it's inactive, stop. It will auto-revalidate when
// refocusing or reconnecting.
// When retrying, deduplication is always enabled.
currentConfig.onErrorRetry(err, key, currentConfig, revalidate, (_tmp3.retryCount = (opts.retryCount || 0) + 1, _tmp3.dedupe = true, _tmp3));
}
}
}
}
return [
3,
4
];
case 4:
// Mark loading as stopped.
loading = false;
// Update the current hook's state.
finishRequestAndUpdateState();
return [
2,
true
];
}
}
});
}), // `setState` is immutable, and `eventsCallback`, `fnArg`, and
}
// Mark loading as stopped.
loading = false;
// Update the current hook's state.
finishRequestAndUpdateState();
return true;
}, // `setState` is immutable, and `eventsCallback`, `fnArg`, and
// `keyValidating` are depending on `key`, so we can exclude them from

@@ -470,15 +309,9 @@ // the deps array.

// eslint-disable-next-line react-hooks/exhaustive-deps
var boundMutate = react.useCallback(// Use callback to make sure `keyRef.current` returns latest result every time
function() {
for(var _len = arguments.length, args = new Array(_len), _$_key = 0; _$_key < _len; _$_key++){
args[_$_key] = arguments[_$_key];
}
return _internal.internalMutate.apply(void 0, [
cache,
keyRef.current
].concat(_toConsumableArray(args)));
const boundMutate = react.useCallback(// Use callback to make sure `keyRef.current` returns latest result every time
(...args)=>{
return _internal.internalMutate(cache, keyRef.current, ...args);
}, // eslint-disable-next-line react-hooks/exhaustive-deps
[]);
// The logic for updating refs.
_internal.useIsomorphicLayoutEffect(function() {
_internal.useIsomorphicLayoutEffect(()=>{
fetcherRef.current = fetcher;

@@ -493,11 +326,11 @@ configRef.current = config;

// After mounted or key changed.
_internal.useIsomorphicLayoutEffect(function() {
_internal.useIsomorphicLayoutEffect(()=>{
if (!key) return;
var softRevalidate = revalidate.bind(_internal.UNDEFINED, WITH_DEDUPE);
const softRevalidate = revalidate.bind(_internal.UNDEFINED, WITH_DEDUPE);
// Expose revalidators to global event listeners. So we can trigger
// revalidation from the outside.
var nextFocusRevalidatedAt = 0;
var onRevalidate = function(type) {
let nextFocusRevalidatedAt = 0;
const onRevalidate = (type)=>{
if (type == _internal.revalidateEvents.FOCUS_EVENT) {
var now = Date.now();
const now = Date.now();
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) {

@@ -516,3 +349,3 @@ nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval;

};
var unsubEvents = _internal.subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);
const unsubEvents = _internal.subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);
// Mark the component as mounted and update corresponding refs.

@@ -537,3 +370,3 @@ unmountedRef.current = false;

}
return function() {
return ()=>{
// Mark it as unmounted.

@@ -547,7 +380,8 @@ unmountedRef.current = true;

// Polling
_internal.useIsomorphicLayoutEffect(function() {
var next = function next() {
_internal.useIsomorphicLayoutEffect(()=>{
let timer;
function next() {
// Use the passed interval
// ...or invoke the function with the updated data to get the interval
var interval = _internal.isFunction(refreshInterval) ? refreshInterval(data) : refreshInterval;
const interval = _internal.isFunction(refreshInterval) ? refreshInterval(data) : refreshInterval;
// We only start the next interval if `refreshInterval` is not 0, and:

@@ -559,4 +393,4 @@ // - `force` is true, which is the start of polling

}
};
var execute = function execute() {
}
function execute() {
// Check if it's OK to execute:

@@ -570,6 +404,5 @@ // Only revalidate when the page is visible, online, and not errored.

}
};
var timer;
}
next();
return function() {
return ()=>{
if (timer) {

@@ -597,3 +430,3 @@ clearTimeout(timer);

if (!_internal.IS_REACT_LEGACY && _internal.IS_SERVER) {
throw new Error("Fallback data is required when using suspense in SSR.");
throw new Error('Fallback data is required when using suspense in SSR.');
}

@@ -626,8 +459,6 @@ // Always update fetcher and config refs even with the Suspense mode.

};
var SWRConfig = _internal.OBJECT.defineProperty(_internal.SWRConfig, "defaultValue", {
const SWRConfig = _internal.OBJECT.defineProperty(_internal.SWRConfig, 'defaultValue', {
value: _internal.defaultConfig
});
var unstable_serialize = function(key) {
return _internal.serialize(key)[0];
};
const unstable_serialize = (key)=>_internal.serialize(key)[0];
/**

@@ -634,0 +465,0 @@ * A hook to fetch data.

@@ -8,4 +8,4 @@ {

"scripts": {
"watch": "bunchee index.ts -w",
"build": "bunchee index.ts",
"watch": "bunchee --target es2018 index.ts -w",
"build": "bunchee --target es2018 index.ts",
"types:check": "tsc --noEmit",

@@ -12,0 +12,0 @@ "clean": "rimraf dist"

import useSWR from 'swr';
import { withMiddleware } from 'swr/_internal';
var immutable = function(useSWRNext) {
return function(key, fetcher, config) {
const immutable = (useSWRNext)=>(key, fetcher, config)=>{
// Always override all revalidate options.

@@ -12,5 +11,4 @@ config.revalidateOnFocus = false;

};
};
var index = withMiddleware(useSWR, immutable);
export { index as default, immutable };

@@ -1,3 +0,1 @@

Object.defineProperty(exports, '__esModule', { value: true });
var useSWR = require('swr');

@@ -10,4 +8,3 @@ var _internal = require('swr/_internal');

var immutable = function(useSWRNext) {
return function(key, fetcher, config) {
const immutable = (useSWRNext)=>(key, fetcher, config)=>{
// Always override all revalidate options.

@@ -19,3 +16,2 @@ config.revalidateOnFocus = false;

};
};
var index = _internal.withMiddleware(useSWR__default["default"], immutable);

@@ -22,0 +18,0 @@

@@ -8,4 +8,4 @@ {

"scripts": {
"watch": "bunchee index.ts -w",
"build": "bunchee index.ts",
"watch": "bunchee --target es2018 index.ts -w",
"build": "bunchee --target es2018 index.ts",
"types:check": "tsc --noEmit",

@@ -12,0 +12,0 @@ "clean": "rimraf dist"

import { useRef, useCallback } from 'react';
import useSWR from 'swr';
import { withMiddleware, serialize, createCacheHelper, isUndefined, useIsomorphicLayoutEffect, isFunction, UNDEFINED } from 'swr/_internal';
import { withMiddleware, createCacheHelper, isUndefined, useIsomorphicLayoutEffect, serialize, UNDEFINED, isFunction } from 'swr/_internal';
import { useSyncExternalStore } from 'use-sync-external-store/shim/index.js';
// We have to several type castings here because `useSWRInfinite` is a special
// hook where `key` and return type are not like the normal `useSWR` types.
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
var __generator = undefined && undefined.__generator || function(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
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 INFINITE_PREFIX = "$inf$";
var EMPTY_PROMISE = Promise.resolve();
var getFirstPageKey = function(getKey) {
const INFINITE_PREFIX = '$inf$';
const EMPTY_PROMISE = Promise.resolve();
const getFirstPageKey = (getKey)=>{
return serialize(getKey ? getKey(0, null) : null)[0];
};
var unstable_serialize = function(getKey) {
const unstable_serialize = (getKey)=>{
return INFINITE_PREFIX + getFirstPageKey(getKey);
};
var infinite = function(useSWRNext) {
return function(getKey, fn, config) {
var didMountRef = useRef(false);
var dataRef = useRef();
var cache = config.cache, _initialSize = config.initialSize, initialSize = _initialSize === void 0 ? 1 : _initialSize, _revalidateAll = config.revalidateAll, revalidateAll = _revalidateAll === void 0 ? false : _revalidateAll, _persistSize = config.persistSize, persistSize = _persistSize === void 0 ? false : _persistSize, _revalidateFirstPage = config.revalidateFirstPage, revalidateFirstPage = _revalidateFirstPage === void 0 ? true : _revalidateFirstPage, _revalidateOnMount = config.revalidateOnMount, revalidateOnMount = _revalidateOnMount === void 0 ? false : _revalidateOnMount;
const infinite = (useSWRNext)=>{
return (getKey, fn, config)=>{
const didMountRef = useRef(false);
const dataRef = useRef();
const { cache , initialSize =1 , revalidateAll =false , persistSize =false , revalidateFirstPage =true , revalidateOnMount =false } = config;
// The serialized key of the first page. This key will be used to store
// metadata of this SWR infinite hook.
var infiniteKey;
let infiniteKey;
try {

@@ -154,5 +29,5 @@ infiniteKey = getFirstPageKey(getKey);

}
var ref = createCacheHelper(cache, infiniteKey), get = ref[0], set = ref[1], subscribeCache = ref[2];
var getSnapshot = useCallback(function() {
var size = isUndefined(get()._l) ? initialSize : get()._l;
const [get, set, subscribeCache] = createCacheHelper(cache, infiniteKey);
const getSnapshot = useCallback(()=>{
const size = isUndefined(get()._l) ? initialSize : get()._l;
return size;

@@ -165,7 +40,7 @@ // eslint-disable-next-line react-hooks/exhaustive-deps

]);
useSyncExternalStore(useCallback(function(callback) {
if (infiniteKey) return subscribeCache(infiniteKey, function() {
useSyncExternalStore(useCallback((callback)=>{
if (infiniteKey) return subscribeCache(infiniteKey, ()=>{
callback();
});
return function() {};
return ()=>{};
}, // eslint-disable-next-line react-hooks/exhaustive-deps

@@ -176,4 +51,4 @@ [

]), getSnapshot, getSnapshot);
var resolvePageSize = useCallback(function() {
var cachedPageSize = get()._l;
const resolvePageSize = useCallback(()=>{
const cachedPageSize = get()._l;
return isUndefined(cachedPageSize) ? initialSize : cachedPageSize;

@@ -187,5 +62,5 @@ // `cache` isn't allowed to change during the lifecycle

// keep the last page size to restore it with the persistSize option
var lastPageSizeRef = useRef(resolvePageSize());
const lastPageSizeRef = useRef(resolvePageSize());
// When the page key changes, we reset the page size if it's not persisted
useIsomorphicLayoutEffect(function() {
useIsomorphicLayoutEffect(()=>{
if (!didMountRef.current) {

@@ -208,68 +83,46 @@ didMountRef.current = true;

// Needs to check didMountRef during mounting, not in the fetcher
var shouldRevalidateOnMount = revalidateOnMount && !didMountRef.current;
const shouldRevalidateOnMount = revalidateOnMount && !didMountRef.current;
// Actual SWR hook to load all pages in one fetcher.
var swr = useSWRNext(infiniteKey, /*#__PURE__*/ _asyncToGenerator(function() {
var ref, forceRevalidateAll, originalData, data, pageSize, previousPageData, i, ref1, pageKey, pageArg, ref2, getSWRCache, setSWRCache, pageData, shouldFetchPage, _tmp, _tmp1;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
ref = get()._i || [], forceRevalidateAll = ref[0], originalData = ref[1];
data = [];
pageSize = resolvePageSize();
previousPageData = null;
i = 0;
_state.label = 1;
case 1:
if (!(i < pageSize)) return [
3,
5
];
ref1 = serialize(getKey(i, previousPageData)), pageKey = ref1[0], pageArg = ref1[1];
if (!pageKey) {
// `pageKey` is falsy, stop fetching new pages.
return [
3,
5
];
}
ref2 = createCacheHelper(cache, pageKey), getSWRCache = ref2[0], setSWRCache = ref2[1];
pageData = getSWRCache().data;
shouldFetchPage = revalidateAll || forceRevalidateAll || isUndefined(pageData) || revalidateFirstPage && !i && !isUndefined(dataRef.current) || shouldRevalidateOnMount || originalData && !isUndefined(originalData[i]) && !config.compare(originalData[i], pageData);
if (!(fn && shouldFetchPage)) return [
3,
3
];
return [
4,
fn(pageArg)
];
case 2:
pageData = _state.sent();
_tmp = {};
setSWRCache((_tmp.data = pageData, _tmp._k = pageArg, _tmp));
_state.label = 3;
case 3:
data.push(pageData);
previousPageData = pageData;
_state.label = 4;
case 4:
++i;
return [
3,
1
];
case 5:
_tmp1 = {};
// once we executed the data fetching based on the context, clear the context
set((_tmp1._i = UNDEFINED, _tmp1));
// return the data
return [
2,
data
];
const swr = useSWRNext(infiniteKey, async ()=>{
// get the revalidate context
const [forceRevalidateAll, originalData] = get()._i || [];
// return an array of page data
const data = [];
const pageSize = resolvePageSize();
let previousPageData = null;
for(let i = 0; i < pageSize; ++i){
const [pageKey, pageArg] = serialize(getKey(i, previousPageData));
if (!pageKey) {
break;
}
const [getSWRCache, setSWRCache] = createCacheHelper(cache, pageKey);
// Get the cached page data.
let pageData = getSWRCache().data;
// should fetch (or revalidate) if:
// - `revalidateAll` is enabled
// - `mutate()` called
// - the cache is missing
// - it's the first page and it's not the initial render
// - `revalidateOnMount` is enabled and it's on mount
// - cache for that page has changed
const shouldFetchPage = revalidateAll || forceRevalidateAll || isUndefined(pageData) || revalidateFirstPage && !i && !isUndefined(dataRef.current) || shouldRevalidateOnMount || originalData && !isUndefined(originalData[i]) && !config.compare(originalData[i], pageData);
if (fn && shouldFetchPage) {
pageData = await fn(pageArg);
setSWRCache({
data: pageData,
_k: pageArg
});
}
data.push(pageData);
previousPageData = pageData;
}
// once we executed the data fetching based on the context, clear the context
set({
_i: UNDEFINED
});
}), config);
// return the data
return data;
}, config);
// update dataRef
useIsomorphicLayoutEffect(function() {
useIsomorphicLayoutEffect(()=>{
dataRef.current = swr.data;

@@ -279,11 +132,11 @@ }, [

]);
var mutate = useCallback(// eslint-disable-next-line func-names
const mutate = useCallback(// eslint-disable-next-line func-names
function(data, opts) {
// When passing as a boolean, it's explicitly used to disable/enable
// revalidation.
var options = typeof opts === "boolean" ? {
const options = typeof opts === 'boolean' ? {
revalidate: opts
} : opts || {};
// Default to true.
var shouldRevalidate = options.revalidate !== false;
const shouldRevalidate = options.revalidate !== false;
// It is possible that the key is still falsy.

@@ -294,3 +147,3 @@ if (!infiniteKey) return EMPTY_PROMISE;

// We only revalidate the pages that are changed
var originalData = dataRef.current;
const originalData = dataRef.current;
set({

@@ -319,11 +172,11 @@ _i: [

// Function to load pages data from the cache based on the page size.
var resolvePagesFromCache = function(pageSize) {
const resolvePagesFromCache = (pageSize)=>{
// return an array of page data
var data = [];
var previousPageData = null;
for(var i = 0; i < pageSize; ++i){
const data = [];
let previousPageData = null;
for(let i = 0; i < pageSize; ++i){
var ref;
var ref1 = serialize(getKey(i, previousPageData)), pageKey = ref1[0];
const [pageKey] = serialize(getKey(i, previousPageData));
// Get the cached page data.
var pageData = pageKey ? (ref = cache.get(pageKey)) == null ? void 0 : ref.data : UNDEFINED;
const pageData = pageKey ? (ref = cache.get(pageKey)) == null ? void 0 : ref.data : UNDEFINED;
// Return the current data if we can't get it from the cache.

@@ -338,12 +191,12 @@ if (isUndefined(pageData)) return dataRef.current;

// Extend the SWR API
var setSize = useCallback(function(arg) {
const setSize = useCallback((arg)=>{
// It is possible that the key is still falsy.
if (!infiniteKey) return EMPTY_PROMISE;
var size;
let size;
if (isFunction(arg)) {
size = arg(resolvePageSize());
} else if (typeof arg == "number") {
} else if (typeof arg == 'number') {
size = arg;
}
if (typeof size != "number") return EMPTY_PROMISE;
if (typeof size != 'number') return EMPTY_PROMISE;
set({

@@ -366,4 +219,4 @@ _l: size

size: resolvePageSize(),
setSize: setSize,
mutate: mutate,
setSize,
mutate,
get data () {

@@ -370,0 +223,0 @@ return swr.data;

@@ -1,3 +0,1 @@

Object.defineProperty(exports, '__esModule', { value: true });
var react = require('react');

@@ -13,143 +11,18 @@ var useSWR = require('swr');

// We have to several type castings here because `useSWRInfinite` is a special
// hook where `key` and return type are not like the normal `useSWR` types.
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
var __generator = undefined && undefined.__generator || function(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
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 INFINITE_PREFIX = "$inf$";
var EMPTY_PROMISE = Promise.resolve();
var getFirstPageKey = function(getKey) {
const INFINITE_PREFIX = '$inf$';
const EMPTY_PROMISE = Promise.resolve();
const getFirstPageKey = (getKey)=>{
return _internal.serialize(getKey ? getKey(0, null) : null)[0];
};
var unstable_serialize = function(getKey) {
const unstable_serialize = (getKey)=>{
return INFINITE_PREFIX + getFirstPageKey(getKey);
};
var infinite = function(useSWRNext) {
return function(getKey, fn, config) {
var didMountRef = react.useRef(false);
var dataRef = react.useRef();
var cache = config.cache, _initialSize = config.initialSize, initialSize = _initialSize === void 0 ? 1 : _initialSize, _revalidateAll = config.revalidateAll, revalidateAll = _revalidateAll === void 0 ? false : _revalidateAll, _persistSize = config.persistSize, persistSize = _persistSize === void 0 ? false : _persistSize, _revalidateFirstPage = config.revalidateFirstPage, revalidateFirstPage = _revalidateFirstPage === void 0 ? true : _revalidateFirstPage, _revalidateOnMount = config.revalidateOnMount, revalidateOnMount = _revalidateOnMount === void 0 ? false : _revalidateOnMount;
const infinite = (useSWRNext)=>{
return (getKey, fn, config)=>{
const didMountRef = react.useRef(false);
const dataRef = react.useRef();
const { cache , initialSize =1 , revalidateAll =false , persistSize =false , revalidateFirstPage =true , revalidateOnMount =false } = config;
// The serialized key of the first page. This key will be used to store
// metadata of this SWR infinite hook.
var infiniteKey;
let infiniteKey;
try {

@@ -161,5 +34,5 @@ infiniteKey = getFirstPageKey(getKey);

}
var ref = _internal.createCacheHelper(cache, infiniteKey), get = ref[0], set = ref[1], subscribeCache = ref[2];
var getSnapshot = react.useCallback(function() {
var size = _internal.isUndefined(get()._l) ? initialSize : get()._l;
const [get, set, subscribeCache] = _internal.createCacheHelper(cache, infiniteKey);
const getSnapshot = react.useCallback(()=>{
const size = _internal.isUndefined(get()._l) ? initialSize : get()._l;
return size;

@@ -172,7 +45,7 @@ // eslint-disable-next-line react-hooks/exhaustive-deps

]);
index_js.useSyncExternalStore(react.useCallback(function(callback) {
if (infiniteKey) return subscribeCache(infiniteKey, function() {
index_js.useSyncExternalStore(react.useCallback((callback)=>{
if (infiniteKey) return subscribeCache(infiniteKey, ()=>{
callback();
});
return function() {};
return ()=>{};
}, // eslint-disable-next-line react-hooks/exhaustive-deps

@@ -183,4 +56,4 @@ [

]), getSnapshot, getSnapshot);
var resolvePageSize = react.useCallback(function() {
var cachedPageSize = get()._l;
const resolvePageSize = react.useCallback(()=>{
const cachedPageSize = get()._l;
return _internal.isUndefined(cachedPageSize) ? initialSize : cachedPageSize;

@@ -194,5 +67,5 @@ // `cache` isn't allowed to change during the lifecycle

// keep the last page size to restore it with the persistSize option
var lastPageSizeRef = react.useRef(resolvePageSize());
const lastPageSizeRef = react.useRef(resolvePageSize());
// When the page key changes, we reset the page size if it's not persisted
_internal.useIsomorphicLayoutEffect(function() {
_internal.useIsomorphicLayoutEffect(()=>{
if (!didMountRef.current) {

@@ -215,68 +88,46 @@ didMountRef.current = true;

// Needs to check didMountRef during mounting, not in the fetcher
var shouldRevalidateOnMount = revalidateOnMount && !didMountRef.current;
const shouldRevalidateOnMount = revalidateOnMount && !didMountRef.current;
// Actual SWR hook to load all pages in one fetcher.
var swr = useSWRNext(infiniteKey, /*#__PURE__*/ _asyncToGenerator(function() {
var ref, forceRevalidateAll, originalData, data, pageSize, previousPageData, i, ref1, pageKey, pageArg, ref2, getSWRCache, setSWRCache, pageData, shouldFetchPage, _tmp, _tmp1;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
ref = get()._i || [], forceRevalidateAll = ref[0], originalData = ref[1];
data = [];
pageSize = resolvePageSize();
previousPageData = null;
i = 0;
_state.label = 1;
case 1:
if (!(i < pageSize)) return [
3,
5
];
ref1 = _internal.serialize(getKey(i, previousPageData)), pageKey = ref1[0], pageArg = ref1[1];
if (!pageKey) {
// `pageKey` is falsy, stop fetching new pages.
return [
3,
5
];
}
ref2 = _internal.createCacheHelper(cache, pageKey), getSWRCache = ref2[0], setSWRCache = ref2[1];
pageData = getSWRCache().data;
shouldFetchPage = revalidateAll || forceRevalidateAll || _internal.isUndefined(pageData) || revalidateFirstPage && !i && !_internal.isUndefined(dataRef.current) || shouldRevalidateOnMount || originalData && !_internal.isUndefined(originalData[i]) && !config.compare(originalData[i], pageData);
if (!(fn && shouldFetchPage)) return [
3,
3
];
return [
4,
fn(pageArg)
];
case 2:
pageData = _state.sent();
_tmp = {};
setSWRCache((_tmp.data = pageData, _tmp._k = pageArg, _tmp));
_state.label = 3;
case 3:
data.push(pageData);
previousPageData = pageData;
_state.label = 4;
case 4:
++i;
return [
3,
1
];
case 5:
_tmp1 = {};
// once we executed the data fetching based on the context, clear the context
set((_tmp1._i = _internal.UNDEFINED, _tmp1));
// return the data
return [
2,
data
];
const swr = useSWRNext(infiniteKey, async ()=>{
// get the revalidate context
const [forceRevalidateAll, originalData] = get()._i || [];
// return an array of page data
const data = [];
const pageSize = resolvePageSize();
let previousPageData = null;
for(let i = 0; i < pageSize; ++i){
const [pageKey, pageArg] = _internal.serialize(getKey(i, previousPageData));
if (!pageKey) {
break;
}
const [getSWRCache, setSWRCache] = _internal.createCacheHelper(cache, pageKey);
// Get the cached page data.
let pageData = getSWRCache().data;
// should fetch (or revalidate) if:
// - `revalidateAll` is enabled
// - `mutate()` called
// - the cache is missing
// - it's the first page and it's not the initial render
// - `revalidateOnMount` is enabled and it's on mount
// - cache for that page has changed
const shouldFetchPage = revalidateAll || forceRevalidateAll || _internal.isUndefined(pageData) || revalidateFirstPage && !i && !_internal.isUndefined(dataRef.current) || shouldRevalidateOnMount || originalData && !_internal.isUndefined(originalData[i]) && !config.compare(originalData[i], pageData);
if (fn && shouldFetchPage) {
pageData = await fn(pageArg);
setSWRCache({
data: pageData,
_k: pageArg
});
}
data.push(pageData);
previousPageData = pageData;
}
// once we executed the data fetching based on the context, clear the context
set({
_i: _internal.UNDEFINED
});
}), config);
// return the data
return data;
}, config);
// update dataRef
_internal.useIsomorphicLayoutEffect(function() {
_internal.useIsomorphicLayoutEffect(()=>{
dataRef.current = swr.data;

@@ -286,11 +137,11 @@ }, [

]);
var mutate = react.useCallback(// eslint-disable-next-line func-names
const mutate = react.useCallback(// eslint-disable-next-line func-names
function(data, opts) {
// When passing as a boolean, it's explicitly used to disable/enable
// revalidation.
var options = typeof opts === "boolean" ? {
const options = typeof opts === 'boolean' ? {
revalidate: opts
} : opts || {};
// Default to true.
var shouldRevalidate = options.revalidate !== false;
const shouldRevalidate = options.revalidate !== false;
// It is possible that the key is still falsy.

@@ -301,3 +152,3 @@ if (!infiniteKey) return EMPTY_PROMISE;

// We only revalidate the pages that are changed
var originalData = dataRef.current;
const originalData = dataRef.current;
set({

@@ -326,11 +177,11 @@ _i: [

// Function to load pages data from the cache based on the page size.
var resolvePagesFromCache = function(pageSize) {
const resolvePagesFromCache = (pageSize)=>{
// return an array of page data
var data = [];
var previousPageData = null;
for(var i = 0; i < pageSize; ++i){
const data = [];
let previousPageData = null;
for(let i = 0; i < pageSize; ++i){
var ref;
var ref1 = _internal.serialize(getKey(i, previousPageData)), pageKey = ref1[0];
const [pageKey] = _internal.serialize(getKey(i, previousPageData));
// Get the cached page data.
var pageData = pageKey ? (ref = cache.get(pageKey)) == null ? void 0 : ref.data : _internal.UNDEFINED;
const pageData = pageKey ? (ref = cache.get(pageKey)) == null ? void 0 : ref.data : _internal.UNDEFINED;
// Return the current data if we can't get it from the cache.

@@ -345,12 +196,12 @@ if (_internal.isUndefined(pageData)) return dataRef.current;

// Extend the SWR API
var setSize = react.useCallback(function(arg) {
const setSize = react.useCallback((arg)=>{
// It is possible that the key is still falsy.
if (!infiniteKey) return EMPTY_PROMISE;
var size;
let size;
if (_internal.isFunction(arg)) {
size = arg(resolvePageSize());
} else if (typeof arg == "number") {
} else if (typeof arg == 'number') {
size = arg;
}
if (typeof size != "number") return EMPTY_PROMISE;
if (typeof size != 'number') return EMPTY_PROMISE;
set({

@@ -373,4 +224,4 @@ _l: size

size: resolvePageSize(),
setSize: setSize,
mutate: mutate,
setSize,
mutate,
get data () {

@@ -377,0 +228,0 @@ return swr.data;

@@ -8,4 +8,4 @@ {

"scripts": {
"watch": "bunchee index.ts -w",
"build": "bunchee index.ts",
"watch": "bunchee --target es2018 index.ts -w",
"build": "bunchee --target es2018 index.ts",
"types:check": "tsc --noEmit",

@@ -12,0 +12,0 @@ "clean": "rimraf dist"

import { useRef, useCallback } from 'react';
import useSWR, { useSWRConfig } from 'swr';
import { withMiddleware, useStateWithDeps, UNDEFINED, getTimestamp, useIsomorphicLayoutEffect, mergeObjects, serialize } from 'swr/_internal';
import { withMiddleware, useStateWithDeps, UNDEFINED, serialize, mergeObjects, getTimestamp, useIsomorphicLayoutEffect } from 'swr/_internal';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
var __generator = undefined && undefined.__generator || function(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
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 mutation = function() {
return function(key, fetcher, config) {
if (config === void 0) config = {};
var mutate = useSWRConfig().mutate;
var keyRef = useRef(key);
const mutation = ()=>{
return (key, fetcher, config = {})=>{
const { mutate } = useSWRConfig();
const keyRef = useRef(key);
// Ditch all mutation results that happened earlier than this timestamp.
var ditchMutationsUntilRef = useRef(0);
var ref = useStateWithDeps({
const ditchMutationsUntilRef = useRef(0);
const [stateRef, stateDependencies, setState] = useStateWithDeps({
data: UNDEFINED,
error: UNDEFINED,
isMutating: false
}), stateRef = ref[0], stateDependencies = ref[1], setState = ref[2];
var currentState = stateRef.current;
var trigger = useCallback(/*#__PURE__*/ _asyncToGenerator(function(arg, opts) {
var ref, serializedKey, resolvedKey, options, _tmp, mutationStartedAt, _tmp1, data, _tmp2, _tmp3, _tmp4, error, _tmp5;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
ref = serialize(keyRef.current), serializedKey = ref[0], resolvedKey = ref[1];
if (!fetcher) {
throw new Error("Can’t trigger the mutation: missing fetcher.");
}
if (!serializedKey) {
throw new Error("Can’t trigger the mutation: missing key.");
}
_tmp = {};
options = mergeObjects(mergeObjects((_tmp.populateCache = false, _tmp.throwOnError = true, _tmp), config), opts);
mutationStartedAt = getTimestamp();
ditchMutationsUntilRef.current = mutationStartedAt;
_tmp1 = {};
setState((_tmp1.isMutating = true, _tmp1));
_state.label = 1;
case 1:
_state.trys.push([
1,
3,
,
4
]);
_tmp2 = {};
_tmp3 = {};
return [
4,
mutate(serializedKey, fetcher(resolvedKey, (_tmp2.arg = arg, _tmp2)), // We must throw the error here so we can catch and update the states.
mergeObjects(options, (_tmp3.throwOnError = true, _tmp3)))
];
case 2:
data = _state.sent();
_tmp4 = {};
// If it's reset after the mutation, we don't broadcast any state change.
if (ditchMutationsUntilRef.current <= mutationStartedAt) {
setState((_tmp4.data = data, _tmp4.isMutating = false, _tmp4.error = undefined, _tmp4));
options.onSuccess == null ? void 0 : options.onSuccess(data, serializedKey, options);
}
return [
2,
data
];
case 3:
error = _state.sent();
_tmp5 = {};
// If it's reset after the mutation, we don't broadcast any state change
// or throw because it's discarded.
if (ditchMutationsUntilRef.current <= mutationStartedAt) {
setState((_tmp5.error = error, _tmp5.isMutating = false, _tmp5));
options.onError == null ? void 0 : options.onError(error, serializedKey, options);
if (options.throwOnError) {
throw error;
}
}
return [
3,
4
];
case 4:
return [
2
];
});
const currentState = stateRef.current;
const trigger = useCallback(async (arg, opts)=>{
const [serializedKey, resolvedKey] = serialize(keyRef.current);
if (!fetcher) {
throw new Error('Can’t trigger the mutation: missing fetcher.');
}
if (!serializedKey) {
throw new Error('Can’t trigger the mutation: missing key.');
}
// Disable cache population by default.
const options = mergeObjects(mergeObjects({
populateCache: false,
throwOnError: true
}, config), opts);
// Trigger a mutation, and also track the timestamp. Any mutation that happened
// earlier this timestamp should be ignored.
const mutationStartedAt = getTimestamp();
ditchMutationsUntilRef.current = mutationStartedAt;
setState({
isMutating: true
});
try {
const data = await mutate(serializedKey, fetcher(resolvedKey, {
arg
}), // We must throw the error here so we can catch and update the states.
mergeObjects(options, {
throwOnError: true
}));
// If it's reset after the mutation, we don't broadcast any state change.
if (ditchMutationsUntilRef.current <= mutationStartedAt) {
setState({
data,
isMutating: false,
error: undefined
});
options.onSuccess == null ? void 0 : options.onSuccess(data, serializedKey, options);
}
});
}), // eslint-disable-next-line react-hooks/exhaustive-deps
return data;
} catch (error) {
// If it's reset after the mutation, we don't broadcast any state change
// or throw because it's discarded.
if (ditchMutationsUntilRef.current <= mutationStartedAt) {
setState({
error: error,
isMutating: false
});
options.onError == null ? void 0 : options.onError(error, serializedKey, options);
if (options.throwOnError) {
throw error;
}
}
}
}, // eslint-disable-next-line react-hooks/exhaustive-deps
[]);
var reset = useCallback(function() {
const reset = useCallback(()=>{
ditchMutationsUntilRef.current = getTimestamp();

@@ -220,3 +79,3 @@ setState({

}, []);
useIsomorphicLayoutEffect(function() {
useIsomorphicLayoutEffect(()=>{
keyRef.current = key;

@@ -228,4 +87,4 @@ });

return {
trigger: trigger,
reset: reset,
trigger,
reset,
get data () {

@@ -232,0 +91,0 @@ stateDependencies.data = true;

@@ -1,3 +0,1 @@

Object.defineProperty(exports, '__esModule', { value: true });
var react = require('react');

@@ -11,209 +9,68 @@ var useSWR = require('swr');

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
var __generator = undefined && undefined.__generator || function(thisArg, body) {
var f, y, t, g, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
};
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 mutation = function() {
return function(key, fetcher, config) {
if (config === void 0) config = {};
var mutate = useSWR.useSWRConfig().mutate;
var keyRef = react.useRef(key);
const mutation = ()=>{
return (key, fetcher, config = {})=>{
const { mutate } = useSWR.useSWRConfig();
const keyRef = react.useRef(key);
// Ditch all mutation results that happened earlier than this timestamp.
var ditchMutationsUntilRef = react.useRef(0);
var ref = _internal.useStateWithDeps({
const ditchMutationsUntilRef = react.useRef(0);
const [stateRef, stateDependencies, setState] = _internal.useStateWithDeps({
data: _internal.UNDEFINED,
error: _internal.UNDEFINED,
isMutating: false
}), stateRef = ref[0], stateDependencies = ref[1], setState = ref[2];
var currentState = stateRef.current;
var trigger = react.useCallback(/*#__PURE__*/ _asyncToGenerator(function(arg, opts) {
var ref, serializedKey, resolvedKey, options, _tmp, mutationStartedAt, _tmp1, data, _tmp2, _tmp3, _tmp4, error, _tmp5;
return __generator(this, function(_state) {
switch(_state.label){
case 0:
ref = _internal.serialize(keyRef.current), serializedKey = ref[0], resolvedKey = ref[1];
if (!fetcher) {
throw new Error("Can’t trigger the mutation: missing fetcher.");
}
if (!serializedKey) {
throw new Error("Can’t trigger the mutation: missing key.");
}
_tmp = {};
options = _internal.mergeObjects(_internal.mergeObjects((_tmp.populateCache = false, _tmp.throwOnError = true, _tmp), config), opts);
mutationStartedAt = _internal.getTimestamp();
ditchMutationsUntilRef.current = mutationStartedAt;
_tmp1 = {};
setState((_tmp1.isMutating = true, _tmp1));
_state.label = 1;
case 1:
_state.trys.push([
1,
3,
,
4
]);
_tmp2 = {};
_tmp3 = {};
return [
4,
mutate(serializedKey, fetcher(resolvedKey, (_tmp2.arg = arg, _tmp2)), // We must throw the error here so we can catch and update the states.
_internal.mergeObjects(options, (_tmp3.throwOnError = true, _tmp3)))
];
case 2:
data = _state.sent();
_tmp4 = {};
// If it's reset after the mutation, we don't broadcast any state change.
if (ditchMutationsUntilRef.current <= mutationStartedAt) {
setState((_tmp4.data = data, _tmp4.isMutating = false, _tmp4.error = undefined, _tmp4));
options.onSuccess == null ? void 0 : options.onSuccess(data, serializedKey, options);
}
return [
2,
data
];
case 3:
error = _state.sent();
_tmp5 = {};
// If it's reset after the mutation, we don't broadcast any state change
// or throw because it's discarded.
if (ditchMutationsUntilRef.current <= mutationStartedAt) {
setState((_tmp5.error = error, _tmp5.isMutating = false, _tmp5));
options.onError == null ? void 0 : options.onError(error, serializedKey, options);
if (options.throwOnError) {
throw error;
}
}
return [
3,
4
];
case 4:
return [
2
];
});
const currentState = stateRef.current;
const trigger = react.useCallback(async (arg, opts)=>{
const [serializedKey, resolvedKey] = _internal.serialize(keyRef.current);
if (!fetcher) {
throw new Error('Can’t trigger the mutation: missing fetcher.');
}
if (!serializedKey) {
throw new Error('Can’t trigger the mutation: missing key.');
}
// Disable cache population by default.
const options = _internal.mergeObjects(_internal.mergeObjects({
populateCache: false,
throwOnError: true
}, config), opts);
// Trigger a mutation, and also track the timestamp. Any mutation that happened
// earlier this timestamp should be ignored.
const mutationStartedAt = _internal.getTimestamp();
ditchMutationsUntilRef.current = mutationStartedAt;
setState({
isMutating: true
});
try {
const data = await mutate(serializedKey, fetcher(resolvedKey, {
arg
}), // We must throw the error here so we can catch and update the states.
_internal.mergeObjects(options, {
throwOnError: true
}));
// If it's reset after the mutation, we don't broadcast any state change.
if (ditchMutationsUntilRef.current <= mutationStartedAt) {
setState({
data,
isMutating: false,
error: undefined
});
options.onSuccess == null ? void 0 : options.onSuccess(data, serializedKey, options);
}
});
}), // eslint-disable-next-line react-hooks/exhaustive-deps
return data;
} catch (error) {
// If it's reset after the mutation, we don't broadcast any state change
// or throw because it's discarded.
if (ditchMutationsUntilRef.current <= mutationStartedAt) {
setState({
error: error,
isMutating: false
});
options.onError == null ? void 0 : options.onError(error, serializedKey, options);
if (options.throwOnError) {
throw error;
}
}
}
}, // eslint-disable-next-line react-hooks/exhaustive-deps
[]);
var reset = react.useCallback(function() {
const reset = react.useCallback(()=>{
ditchMutationsUntilRef.current = _internal.getTimestamp();

@@ -227,3 +84,3 @@ setState({

}, []);
_internal.useIsomorphicLayoutEffect(function() {
_internal.useIsomorphicLayoutEffect(()=>{
keyRef.current = key;

@@ -235,4 +92,4 @@ });

return {
trigger: trigger,
reset: reset,
trigger,
reset,
get data () {

@@ -239,0 +96,0 @@ stateDependencies.data = true;

@@ -71,2 +71,2 @@ import { Key, MutatorOptions, SWRResponse } from 'swr';

export { SWRMutationConfiguration, SWRMutationHook, SWRMutationResponse, _default as default };
export { MutationFetcher, SWRMutationConfiguration, SWRMutationHook, SWRMutationResponse, _default as default };

@@ -8,4 +8,4 @@ {

"scripts": {
"watch": "bunchee index.ts -w",
"build": "bunchee index.ts",
"watch": "bunchee --target es2018 index.ts -w",
"build": "bunchee --target es2018 index.ts",
"types:check": "tsc --noEmit",

@@ -12,0 +12,0 @@ "clean": "rimraf dist"

{
"name": "swr",
"version": "2.0.0-rc.0",
"version": "2.0.0-rc.1",
"description": "React Hooks library for remote data fetching",

@@ -65,2 +65,21 @@ "keywords": [

"license": "MIT",
"scripts": {
"prepare": "husky install",
"csb:install": "pnpm i -g pnpm@7",
"csb:build": "pnpm install && pnpm build",
"clean": "pnpm -r run clean",
"watch": "pnpm -r run watch",
"build": "pnpm build-package _internal && pnpm build-package core && pnpm build-package infinite && pnpm build-package immutable && pnpm build-package mutation",
"build-package": "bunchee --target es2018 index.ts --cwd",
"types:check": "pnpm -r run types:check",
"prepublishOnly": "pnpm clean && pnpm build",
"publish-beta": "pnpm publish --tag beta",
"format": "prettier --write ./**/*.{ts,tsx}",
"lint": "eslint . --ext .ts,.tsx --cache",
"lint:fix": "pnpm lint --fix",
"coverage": "jest --coverage",
"test-typing": "tsc --noEmit -p test/type/tsconfig.json && tsc --noEmit -p test/tsconfig.json",
"test": "jest",
"run-all-checks": "pnpm types:check && pnpm lint && pnpm test && pnpm test-typing"
},
"lint-staged": {

@@ -73,4 +92,4 @@ "*.{ts,tsx}": [

"devDependencies": {
"@swc/core": "1.2.244",
"@swc/jest": "0.2.21",
"@swc/core": "^1.3.5",
"@swc/jest": "0.2.23",
"@testing-library/jest-dom": "^5.16.4",

@@ -85,3 +104,3 @@ "@testing-library/react": "^13.1.1",

"@typescript-eslint/parser": "5.36.1",
"bunchee": "2.1.1",
"bunchee": "2.1.6",
"eslint": "8.15.0",

@@ -102,3 +121,3 @@ "eslint-config-prettier": "8.5.0",

"rimraf": "3.0.2",
"swr": "2.0.0-rc.0",
"swr": "workspace:*",
"tslib": "2.4.0",

@@ -123,19 +142,3 @@ "typescript": "4.8.2"

"use-sync-external-store": "^1.2.0"
},
"scripts": {
"csb:install": "pnpm i -g pnpm@7",
"csb:build": "pnpm install && pnpm build",
"clean": "pnpm -r run clean",
"watch": "pnpm -r run watch",
"build": "pnpm -r run build",
"types:check": "pnpm -r run types:check",
"publish-beta": "pnpm publish --tag beta",
"format": "prettier --write ./**/*.{ts,tsx}",
"lint": "eslint . --ext .ts,.tsx --cache",
"lint:fix": "pnpm lint --fix",
"coverage": "jest --coverage",
"test-typing": "tsc --noEmit -p test/type/tsconfig.json && tsc --noEmit -p test/tsconfig.json",
"test": "jest",
"run-all-checks": "pnpm types:check && pnpm lint && pnpm test && pnpm test-typing"
}
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc