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

swr

Package Overview
Dependencies
Maintainers
58
Versions
166
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 0.2.2 to 0.2.3-beta.0

2

dist/index.js

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

module.exports=function(e,t){"use strict";var r={};function __webpack_require__(t){if(r[t]){return r[t].exports}var n=r[t]={i:t,l:false,exports:{}};e[t].call(n.exports,n,n.exports,__webpack_require__);n.l=true;return n.exports}__webpack_require__.ab=__dirname+"/";function startup(){return __webpack_require__(325)}return startup()}({202:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:true});var r=new WeakMap;var n=0;function hash(e){if(!e.length)return"";var t="arg";for(var a=0;a<e.length;++a){var i=void 0;if(e[a]===null||typeof e[a]!=="object"){if(typeof e[a]==="string"){i='"'+e[a]+'"'}else{i=String(e[a])}}else{if(!r.has(e[a])){i=n;r.set(e[a],n++)}else{i=r.get(e[a])}}t+="@"+i}return t}t.default=hash},205:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:true});function isOnline(){if(typeof navigator.onLine!=="undefined"){return navigator.onLine}return true}t.default=isOnline},209:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:true});var n=r(297);var a=n.createContext({});a.displayName="SWRConfigContext";t.default=a},297:function(e){e.exports=require("react")},325:function(e,t,r){"use strict";function __export(e){for(var r in e)if(!t.hasOwnProperty(r))t[r]=e[r]}var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});__export(r(516));var a=n(r(516));var i=r(926);t.useSWRPages=i.useSWRPages;var u=r(641);t.cache=u.cache;t.default=a.default},459:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:true});function isDocumentVisible(){if(typeof document!=="undefined"&&typeof document.visibilityState!=="undefined"){return document.visibilityState!=="hidden"}return true}t.default=isDocumentVisible},516:function(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){function adopt(e){return e instanceof r?e:new r(function(t){t(e)})}return new(r||(r=Promise))(function(r,a){function fulfilled(e){try{step(n.next(e))}catch(e){a(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){a(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,t||[])).next())})};var a=this&&this.__generator||function(e,t){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,a,i,u;return u={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(u[Symbol.iterator]=function(){return this}),u;function verb(e){return function(t){return step([e,t])}}function step(u){if(n)throw new TypeError("Generator is already executing.");while(r)try{if(n=1,a&&(i=u[0]&2?a["return"]:u[0]?a["throw"]||((i=a["return"])&&i.call(a),0):a.next)&&!(i=i.call(a,u[1])).done)return i;if(a=0,i)u=[u[0]&2,i.value];switch(u[0]){case 0:case 1:i=u;break;case 4:r.label++;return{value:u[1],done:false};case 5:r.label++;a=u[1];u=[0];continue;case 7:u=r.ops.pop();r.trys.pop();continue;default:if(!(i=r.trys,i=i.length>0&&i[i.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){r.label=u[1];break}if(u[0]===6&&r.label<i[1]){r.label=i[1];i=u;break}if(i&&r.label<i[2]){r.label=i[2];r.ops.push(u);break}if(i[2])r.ops.pop();r.trys.pop();continue}u=t.call(e,r)}catch(e){u=[6,e];a=0}finally{n=i=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:true}}};var i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(Object.hasOwnProperty.call(e,r))t[r]=e[r];t["default"]=e;return t};var u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});var f=r(297);var o=i(r(641));var s=u(r(459));var l=u(r(205));var c=u(r(542));var d=u(r(209));var v=typeof window==="undefined";var p=v?f.useEffect:f.useLayoutEffect;var h=function(e,t){if(t===void 0){t=true}var r=o.cache.serializeKey(e),n=r[0],a=r[2];if(!n)return;var i=o.CACHE_REVALIDATORS[n];if(n&&i){var u=o.cache.get(n);var f=o.cache.get(a);for(var s=0;s<i.length;++s){i[s](t,u,f,s>0)}}};t.trigger=h;var _=function(e,t,r){var n=o.CACHE_REVALIDATORS[e];if(e&&n){for(var a=0;a<n.length;++a){n[a](false,t,r)}}};var R=function(e,t,r){if(r===void 0){r=true}return n(void 0,void 0,void 0,function(){var n,i,u,f,s,l,c;return a(this,function(a){switch(a.label){case 0:n=o.cache.serializeKey(e)[0];if(!n)return[2];if(typeof t==="undefined")return[2,h(e,r)];o.MUTATION_TS[n]=Date.now()-1;if(!(t&&typeof t==="function"))return[3,5];a.label=1;case 1:a.trys.push([1,3,,4]);return[4,t(o.cache.get(n))];case 2:i=a.sent();return[3,4];case 3:f=a.sent();u=f;return[3,4];case 4:return[3,11];case 5:if(!(t&&typeof t.then==="function"))return[3,10];a.label=6;case 6:a.trys.push([6,8,,9]);return[4,t];case 7:i=a.sent();return[3,9];case 8:s=a.sent();u=s;return[3,9];case 9:return[3,11];case 10:i=t;a.label=11;case 11:if(typeof i!=="undefined"){o.cache.set(n,i,false)}l=o.CACHE_REVALIDATORS[n];if(l){for(c=0;c<l.length;++c){l[c](!!r,i,u,c>0)}}if(u)throw u;return[2,i]}})})};t.mutate=R;function useSWR(){var e=this;var t=[];for(var r=0;r<arguments.length;r++){t[r]=arguments[r]}var i,u,h={};if(t.length>=1){i=t[0]}if(t.length>2){u=t[1];h=t[2]}else{if(typeof t[1]==="function"){u=t[1]}else if(typeof t[1]==="object"){h=t[1]}}var O=o.cache.serializeKey(i),y=O[0],S=O[1],C=O[2];h=Object.assign({},o.default,f.useContext(d.default),h);if(typeof u==="undefined"){u=h.fetcher}var E=o.cache.get(y)||h.initialData;var b=o.cache.get(C);var g=f.useRef({data:false,error:false,isValidating:false});var T=f.useRef({data:E,error:b,isValidating:false});var w=f.useState(null)[1];var I=f.useCallback(function(e){var t=false;for(var r in e){T.current[r]=e[r];if(g.current[r]){t=true}}if(t||h.suspense){w({})}},[]);var M=f.useRef(false);var m=f.useRef(y);var A=f.useCallback(function(e,t){return R(y,e,t)},[y]);var N=f.useCallback(function(t){if(t===void 0){t={}}return n(e,void 0,void 0,function(){var e,r,n,i,f,s,l;return a(this,function(a){switch(a.label){case 0:if(!y||!u)return[2,false];if(M.current)return[2,false];t=Object.assign({dedupe:false},t);e=true;r=typeof o.CONCURRENT_PROMISES[y]!=="undefined"&&t.dedupe;a.label=1;case 1:a.trys.push([1,6,,7]);I({isValidating:true});n=void 0;i=void 0;if(!r)return[3,3];i=o.CONCURRENT_PROMISES_TS[y];return[4,o.CONCURRENT_PROMISES[y]];case 2:n=a.sent();return[3,5];case 3:if(o.CONCURRENT_PROMISES[y]){o.MUTATION_TS[y]=Date.now()-1}if(h.loadingTimeout&&!o.cache.get(y)){setTimeout(function(){if(e)h.onLoadingSlow(y,h)},h.loadingTimeout)}if(S!==null){o.CONCURRENT_PROMISES[y]=u.apply(void 0,S)}else{o.CONCURRENT_PROMISES[y]=u(y)}o.CONCURRENT_PROMISES_TS[y]=i=Date.now();return[4,o.CONCURRENT_PROMISES[y]];case 4:n=a.sent();setTimeout(function(){delete o.CONCURRENT_PROMISES[y];delete o.CONCURRENT_PROMISES_TS[y]},h.dedupingInterval);h.onSuccess(n,y,h);a.label=5;case 5:if(o.MUTATION_TS[y]&&i<=o.MUTATION_TS[y]){I({isValidating:false});return[2,false]}o.cache.set(y,n,false);o.cache.set(C,undefined,false);f={isValidating:false};if(typeof T.current.error!=="undefined"){f.error=undefined}if(!h.compare(T.current.data,n)){f.data=n}I(f);if(!r){_(y,n,undefined)}return[3,7];case 6:s=a.sent();delete o.CONCURRENT_PROMISES[y];delete o.CONCURRENT_PROMISES_TS[y];o.cache.set(C,s,false);if(T.current.error!==s){I({isValidating:false,error:s});if(!r){_(y,undefined,s)}}h.onError(s,y,h);if(h.shouldRetryOnError){l=(t.retryCount||0)+1;h.onErrorRetry(s,y,h,N,Object.assign({dedupe:true},t,{retryCount:l}))}return[3,7];case 7:e=false;return[2,true]}})})},[y]);p(function(){if(!y)return undefined;M.current=false;var e=T.current.data;var t=o.cache.get(y)||h.initialData;if(m.current!==y||!h.compare(e,t)){I({data:t});m.current=y}var r=function(){return N({dedupe:true})};if(h.revalidateOnMount||!h.initialData&&h.revalidateOnMount===undefined){if(typeof t!=="undefined"&&!v&&window["requestIdleCallback"]){window["requestIdleCallback"](r)}else{r()}}var n;if(h.revalidateOnFocus){n=c.default(r,h.focusThrottleInterval);if(!o.FOCUS_REVALIDATORS[y]){o.FOCUS_REVALIDATORS[y]=[n]}else{o.FOCUS_REVALIDATORS[y].push(n)}}var a=function(e,t,n,a){if(e===void 0){e=true}if(a===void 0){a=true}var i={};var u=false;if(typeof t!=="undefined"&&!h.compare(T.current.data,t)){i.data=t;u=true}if(T.current.error!==n){i.error=n;u=true}if(u){I(i)}if(e){if(a){return r()}else{return N()}}return false};if(!o.CACHE_REVALIDATORS[y]){o.CACHE_REVALIDATORS[y]=[a]}else{o.CACHE_REVALIDATORS[y].push(a)}var i=null;if(!v&&window.addEventListener&&h.revalidateOnReconnect){window.addEventListener("online",i=r)}return function(){I=function(){return null};M.current=true;if(n&&o.FOCUS_REVALIDATORS[y]){var e=o.FOCUS_REVALIDATORS[y];var t=e.indexOf(n);if(t>=0){e[t]=e[e.length-1];e.pop()}}if(o.CACHE_REVALIDATORS[y]){var e=o.CACHE_REVALIDATORS[y];var t=e.indexOf(a);if(t>=0){e[t]=e[e.length-1];e.pop()}}if(!v&&window.removeEventListener&&i!==null){window.removeEventListener("online",i)}}},[y,N]);p(function(){var t=null;var r=function(){return n(e,void 0,void 0,function(){return a(this,function(e){switch(e.label){case 0:if(!(!T.current.error&&(h.refreshWhenHidden||s.default())&&(h.refreshWhenOffline||l.default())))return[3,2];return[4,N({dedupe:true})];case 1:e.sent();e.label=2;case 2:if(h.refreshInterval){t=setTimeout(r,h.refreshInterval)}return[2]}})})};if(h.refreshInterval){t=setTimeout(r,h.refreshInterval)}return function(){if(t)clearTimeout(t)}},[h.refreshInterval,h.refreshWhenHidden,h.refreshWhenOffline,N]);if(h.suspense){var P=o.cache.get(y);var V=o.cache.get(C);if(typeof P==="undefined"&&typeof V==="undefined"){if(!o.CONCURRENT_PROMISES[y]){N()}if(o.CONCURRENT_PROMISES[y]&&typeof o.CONCURRENT_PROMISES[y].then==="function"){throw o.CONCURRENT_PROMISES[y]}P=o.CONCURRENT_PROMISES[y]}if(typeof P==="undefined"&&V){throw V}return{error:V,data:P,revalidate:N,mutate:A,isValidating:T.current.isValidating}}return f.useMemo(function(){var e={revalidate:N,mutate:A};Object.defineProperties(e,{error:{get:function(){g.current.error=true;return m.current===y?T.current.error:b}},data:{get:function(){g.current.data=true;return m.current===y?T.current.data:E}},isValidating:{get:function(){g.current.isValidating=true;return T.current.isValidating}}});return e},[N])}var O=d.default.Provider;t.SWRConfig=O;t.default=useSWR},542:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:true});function throttle(e,t){var r=false;return function(){var n=[];for(var a=0;a<arguments.length;a++){n[a]=arguments[a]}if(r)return;r=true;e.apply(void 0,n);setTimeout(function(){return r=false},t)}}t.default=throttle},641:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});var a=n(r(832));var i=n(r(459));var u=n(r(205));var f=n(r(722));var o=new f.default;t.cache=o;var s={};t.CONCURRENT_PROMISES=s;var l={};t.CONCURRENT_PROMISES_TS=l;var c={};t.FOCUS_REVALIDATORS=c;var d={};t.CACHE_REVALIDATORS=d;var v={};t.MUTATION_TS=v;function onErrorRetry(e,t,r,n,a){if(!i.default()){return}if(r.errorRetryCount&&a.retryCount>r.errorRetryCount){return}var u=Math.min(a.retryCount||0,8);var f=~~((Math.random()+.5)*(1<<u))*r.errorRetryInterval;setTimeout(n,f,a)}var p=typeof window!=="undefined"&&navigator["connection"]&&["slow-2g","2g"].indexOf(navigator["connection"].effectiveType)!==-1;var h={onLoadingSlow:function(){},onSuccess:function(){},onError:function(){},onErrorRetry:onErrorRetry,errorRetryInterval:(p?10:5)*1e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:(p?5:3)*1e3,refreshInterval:0,revalidateOnFocus:true,revalidateOnReconnect:true,refreshWhenHidden:false,refreshWhenOffline:false,shouldRetryOnError:true,suspense:false,compare:a.default};var _=false;if(typeof window!=="undefined"&&window.addEventListener&&!_){var R=function(){if(!i.default()||!u.default())return;for(var e in c){if(c[e][0])c[e][0]()}};window.addEventListener("visibilitychange",R,false);window.addEventListener("focus",R,false);_=true}t.default=h},722:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});var a=r(516);var i=n(r(202));var u=function(){function Cache(e){if(e===void 0){e={}}this.__cache=new Map(Object.entries(e));this.__listeners=[]}Cache.prototype.get=function(e){var t=this.serializeKey(e)[0];return this.__cache.get(t)};Cache.prototype.set=function(e,t,r){if(r===void 0){r=true}var n=this.serializeKey(e)[0];this.__cache.set(n,t);if(r)a.mutate(e,t,false);this.notify()};Cache.prototype.keys=function(){return Array.from(this.__cache.keys())};Cache.prototype.has=function(e){var t=this.serializeKey(e)[0];return this.__cache.has(t)};Cache.prototype.clear=function(e){if(e===void 0){e=true}if(e)this.__cache.forEach(function(e){return a.mutate(e,null,false)});this.__cache.clear();this.notify()};Cache.prototype.delete=function(e,t){if(t===void 0){t=true}var r=this.serializeKey(e)[0];if(t)a.mutate(e,null,false);this.__cache.delete(r);this.notify()};Cache.prototype.serializeKey=function(e){var t=null;if(typeof e==="function"){try{e=e()}catch(t){e=""}}if(Array.isArray(e)){t=e;e=i.default(e)}else{e=String(e||"")}var r=e?"err@"+e:"";return[e,t,r]};Cache.prototype.subscribe=function(e){var t=this;if(typeof e!=="function"){throw new Error("Expected the listener to be a function.")}var r=true;this.__listeners.push(e);return function(){if(!r)return;r=false;var n=t.__listeners.indexOf(e);if(n>-1){t.__listeners[n]=t.__listeners[t.__listeners.length-1];t.__listeners.length--}}};Cache.prototype.notify=function(){for(var e=0,t=this.__listeners;e<t.length;e++){var r=t[e];r()}};return Cache}();t.default=u},832:function(e){"use strict";e.exports=function equal(e,t){if(e===t)return true;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return false;var r,n,a;if(Array.isArray(e)){r=e.length;if(r!=t.length)return false;for(n=r;n--!==0;)if(!equal(e[n],t[n]))return false;return true}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();a=Object.keys(e);r=a.length;if(r!==Object.keys(t).length)return false;for(n=r;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[n]))return false;for(n=r;n--!==0;){var i=a[n];if(!equal(e[i],t[i]))return false}return true}return e!==e&&t!==t}},926:function(e,t,r){"use strict";var n=this&&this.__spreadArrays||function(){for(var e=0,t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;for(var n=Array(e),a=0,t=0;t<r;t++)for(var i=arguments[t],u=0,f=i.length;u<f;u++,a++)n[a]=i[u];return n};var a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)if(Object.hasOwnProperty.call(e,r))t[r]=e[r];t["default"]=e;return t};Object.defineProperty(t,"__esModule",{value:true});var i=a(r(297));var u=r(641);var f=new Map;function useSWRPages(e,t,r,a){if(a===void 0){a=[]}var o="_swr_page_count_"+e;var s="_swr_page_offset_"+e;var l=i.useState(u.cache.get(o)||1),c=l[0],d=l[1];var v=i.useState(u.cache.get(s)||[null]),p=v[0],h=v[1];var _=i.useState([]),R=_[0],O=_[1];var y=i.useRef(t);var S=i.useRef(false);var C=i.useCallback(function(e){var t=y.current(e);if(t&&!t.length){S.current=true}else{S.current=false}return t},[]);var E=p[c]===null;var b=c===p.length;var g=E&&c===1&&S.current;var T=i.useCallback(function(){if(b||E)return;d(function(e){u.cache.set(o,e+1);return e+1})},[b||E]);var w=i.useCallback(t,a);y.current=w;var I=i.useMemo(function(){var t=function(e){return function(t){if(!R[e]||R[e].data!==t.data||R[e].error!==t.error||R[e].revalidate!==t.revalidate){setTimeout(function(){O(function(r){var a=n(r);a[e]={data:t.data,error:t.error,revalidate:t.revalidate,isValidating:t.isValidating,mutate:t.mutate};return a});if(typeof t.data!=="undefined"){var a=r(t,e);if(p[e+1]!==a){h(function(t){var r=n(t);r[e+1]=a;u.cache.set(s,r);return r})}}})}return t}};var a=[];if(!f.has(e)){f.set(e,[])}var o=f.get(e);for(var l=0;l<c;++l){if(!o[l]||o[l].offset!==p[l]||o[l].pageFn!==w){o[l]={component:i.default.createElement(C,{key:"page-"+p[l]+"-"+l,offset:p[l],withSWR:t(l)}),pageFn:w,offset:p[l]}}a.push(o[l].component)}return a},[w,c,R,p,e]);return{pages:I,pageCount:c,pageSWRs:R,isLoadingMore:b,isReachingEnd:E,isEmpty:g,loadMore:T}}t.useSWRPages=useSWRPages}});
module.exports=function(e,r){"use strict";var t={};function __webpack_require__(r){if(t[r]){return t[r].exports}var n=t[r]={i:r,l:false,exports:{}};e[r].call(n.exports,n,n.exports,__webpack_require__);n.l=true;return n.exports}__webpack_require__.ab=__dirname+"/";function startup(){return __webpack_require__(325)}return startup()}({202:function(e,r){"use strict";Object.defineProperty(r,"__esModule",{value:true});var t=new WeakMap;var n=0;function hash(e){if(!e.length)return"";var r="arg";for(var a=0;a<e.length;++a){var i=void 0;if(e[a]===null||typeof e[a]!=="object"){if(typeof e[a]==="string"){i='"'+e[a]+'"'}else{i=String(e[a])}}else{if(!t.has(e[a])){i=n;t.set(e[a],n++)}else{i=t.get(e[a])}}r+="@"+i}return r}r.default=hash},205:function(e,r){"use strict";Object.defineProperty(r,"__esModule",{value:true});function isOnline(){if(typeof navigator.onLine!=="undefined"){return navigator.onLine}return true}r.default=isOnline},209:function(e,r,t){"use strict";Object.defineProperty(r,"__esModule",{value:true});var n=t(297);var a=n.createContext({});a.displayName="SWRConfigContext";r.default=a},297:function(e){e.exports=require("react")},325:function(e,r,t){"use strict";function __export(e){for(var t in e)if(!r.hasOwnProperty(t))r[t]=e[t]}var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:true});__export(t(516));var a=n(t(516));var i=t(926);r.useSWRPages=i.useSWRPages;var u=t(641);r.cache=u.cache;r.default=a.default},459:function(e,r){"use strict";Object.defineProperty(r,"__esModule",{value:true});function isDocumentVisible(){if(typeof document!=="undefined"&&typeof document.visibilityState!=="undefined"){return document.visibilityState!=="hidden"}return true}r.default=isDocumentVisible},516:function(e,r,t){"use strict";var n=this&&this.__awaiter||function(e,r,t,n){function adopt(e){return e instanceof t?e:new t(function(r){r(e)})}return new(t||(t=Promise))(function(t,a){function fulfilled(e){try{step(n.next(e))}catch(e){a(e)}}function rejected(e){try{step(n["throw"](e))}catch(e){a(e)}}function step(e){e.done?t(e.value):adopt(e.value).then(fulfilled,rejected)}step((n=n.apply(e,r||[])).next())})};var a=this&&this.__generator||function(e,r){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,a,i,u;return u={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol==="function"&&(u[Symbol.iterator]=function(){return this}),u;function verb(e){return function(r){return step([e,r])}}function step(u){if(n)throw new TypeError("Generator is already executing.");while(t)try{if(n=1,a&&(i=u[0]&2?a["return"]:u[0]?a["throw"]||((i=a["return"])&&i.call(a),0):a.next)&&!(i=i.call(a,u[1])).done)return i;if(a=0,i)u=[u[0]&2,i.value];switch(u[0]){case 0:case 1:i=u;break;case 4:t.label++;return{value:u[1],done:false};case 5:t.label++;a=u[1];u=[0];continue;case 7:u=t.ops.pop();t.trys.pop();continue;default:if(!(i=t.trys,i=i.length>0&&i[i.length-1])&&(u[0]===6||u[0]===2)){t=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){t.label=u[1];break}if(u[0]===6&&t.label<i[1]){t.label=i[1];i=u;break}if(i&&t.label<i[2]){t.label=i[2];t.ops.push(u);break}if(i[2])t.ops.pop();t.trys.pop();continue}u=r.call(e,t)}catch(e){u=[6,e];a=0}finally{n=i=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:true}}};var i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var t in e)if(Object.hasOwnProperty.call(e,t))r[t]=e[t];r["default"]=e;return r};var u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:true});var f=t(297);var o=i(t(641));var s=u(t(459));var l=u(t(205));var c=u(t(542));var d=u(t(209));var v=typeof window==="undefined";var h=v?f.useEffect:f.useLayoutEffect;var p=function(e,r){if(r===void 0){r=true}var t=o.cache.serializeKey(e),n=t[0],a=t[2];if(!n)return;var i=o.CACHE_REVALIDATORS[n];if(n&&i){var u=o.cache.get(n);var f=o.cache.get(a);for(var s=0;s<i.length;++s){i[s](r,u,f,s>0)}}};r.trigger=p;var _=function(e,r,t){var n=o.CACHE_REVALIDATORS[e];if(e&&n){for(var a=0;a<n.length;++a){n[a](false,r,t)}}};var R=function(e,r,t){if(t===void 0){t=true}return n(void 0,void 0,void 0,function(){var n,i,u,f,s,l,c,d,v;return a(this,function(a){switch(a.label){case 0:n=o.cache.serializeKey(e)[0];if(!n)return[2];if(typeof r==="undefined")return[2,p(e,t)];o.MUTATION_TS[n]=Date.now()-1;f=o.MUTATION_TS[n];s=o.CONCURRENT_PROMISES_TS[n];if(!(r&&typeof r==="function"))return[3,5];a.label=1;case 1:a.trys.push([1,3,,4]);return[4,r(o.cache.get(n))];case 2:i=a.sent();return[3,4];case 3:l=a.sent();u=l;return[3,4];case 4:return[3,11];case 5:if(!(r&&typeof r.then==="function"))return[3,10];a.label=6;case 6:a.trys.push([6,8,,9]);return[4,r];case 7:i=a.sent();return[3,9];case 8:c=a.sent();u=c;return[3,9];case 9:return[3,11];case 10:i=r;a.label=11;case 11:if(f!==o.MUTATION_TS[n]||s!==o.CONCURRENT_PROMISES_TS[n]){if(u)throw u;return[2,i]}if(typeof i!=="undefined"){o.cache.set(n,i,false)}d=o.CACHE_REVALIDATORS[n];if(d){for(v=0;v<d.length;++v){d[v](!!t,i,u,v>0)}}if(u)throw u;return[2,i]}})})};r.mutate=R;function useSWR(){var e=this;var r=[];for(var t=0;t<arguments.length;t++){r[t]=arguments[t]}var i,u,p={};if(r.length>=1){i=r[0]}if(r.length>2){u=r[1];p=r[2]}else{if(typeof r[1]==="function"){u=r[1]}else if(typeof r[1]==="object"){p=r[1]}}var O=o.cache.serializeKey(i),S=O[0],y=O[1],C=O[2];p=Object.assign({},o.default,f.useContext(d.default),p);if(typeof u==="undefined"){u=p.fetcher}var E=o.cache.get(S)||p.initialData;var T=o.cache.get(C);var b=f.useRef({data:false,error:false,isValidating:false});var g=f.useRef({data:E,error:T,isValidating:false});var w=f.useState(null)[1];var m=f.useCallback(function(e){var r=false;for(var t in e){g.current[t]=e[t];if(b.current[t]){r=true}}if(r||p.suspense){w({})}},[]);var I=f.useRef(false);var M=f.useRef(S);var A=f.useRef({emit:function(e){var r=[];for(var t=1;t<arguments.length;t++){r[t-1]=arguments[t]}if(I.current)return;p[e].apply(p,r)}});var N=f.useCallback(function(e,r){return R(S,e,r)},[S]);var P=f.useCallback(function(r){if(r===void 0){r={}}return n(e,void 0,void 0,function(){var e,t,n,i,f,s,l;return a(this,function(a){switch(a.label){case 0:if(!S||!u)return[2,false];if(I.current)return[2,false];r=Object.assign({dedupe:false},r);e=true;t=typeof o.CONCURRENT_PROMISES[S]!=="undefined"&&r.dedupe;a.label=1;case 1:a.trys.push([1,6,,7]);m({isValidating:true});n=void 0;i=void 0;if(!t)return[3,3];i=o.CONCURRENT_PROMISES_TS[S];return[4,o.CONCURRENT_PROMISES[S]];case 2:n=a.sent();return[3,5];case 3:if(o.CONCURRENT_PROMISES[S]){o.MUTATION_TS[S]=Date.now()-1}if(p.loadingTimeout&&!o.cache.get(S)){setTimeout(function(){if(e)A.current.emit("onLoadingSlow",S,p)},p.loadingTimeout)}if(y!==null){o.CONCURRENT_PROMISES[S]=u.apply(void 0,y)}else{o.CONCURRENT_PROMISES[S]=u(S)}o.CONCURRENT_PROMISES_TS[S]=i=Date.now();return[4,o.CONCURRENT_PROMISES[S]];case 4:n=a.sent();setTimeout(function(){delete o.CONCURRENT_PROMISES[S];delete o.CONCURRENT_PROMISES_TS[S]},p.dedupingInterval);A.current.emit("onSuccess",n,S,p);a.label=5;case 5:if(o.MUTATION_TS[S]&&i<=o.MUTATION_TS[S]){m({isValidating:false});return[2,false]}o.cache.set(S,n,false);o.cache.set(C,undefined,false);f={isValidating:false};if(typeof g.current.error!=="undefined"){f.error=undefined}if(!p.compare(g.current.data,n)){f.data=n}m(f);if(!t){_(S,n,undefined)}return[3,7];case 6:s=a.sent();delete o.CONCURRENT_PROMISES[S];delete o.CONCURRENT_PROMISES_TS[S];o.cache.set(C,s,false);if(g.current.error!==s){m({isValidating:false,error:s});if(!t){_(S,undefined,s)}}A.current.emit("onError",s,S,p);if(p.shouldRetryOnError){l=(r.retryCount||0)+1;A.current.emit("onErrorRetry",s,S,p,P,Object.assign({dedupe:true},r,{retryCount:l}))}return[3,7];case 7:e=false;return[2,true]}})})},[S]);h(function(){if(!S)return undefined;I.current=false;var e=g.current.data;var r=o.cache.get(S)||p.initialData;if(M.current!==S||!p.compare(e,r)){m({data:r});M.current=S}var t=function(){return P({dedupe:true})};if(p.revalidateOnMount||!p.initialData&&p.revalidateOnMount===undefined){if(typeof r!=="undefined"&&!v&&window["requestIdleCallback"]){window["requestIdleCallback"](t)}else{t()}}var n;if(p.revalidateOnFocus){n=c.default(t,p.focusThrottleInterval);if(!o.FOCUS_REVALIDATORS[S]){o.FOCUS_REVALIDATORS[S]=[n]}else{o.FOCUS_REVALIDATORS[S].push(n)}}var a=function(e,r,n,a){if(e===void 0){e=true}if(a===void 0){a=true}var i={};var u=false;if(typeof r!=="undefined"&&!p.compare(g.current.data,r)){i.data=r;u=true}if(g.current.error!==n){i.error=n;u=true}if(u){m(i)}if(e){if(a){return t()}else{return P()}}return false};if(!o.CACHE_REVALIDATORS[S]){o.CACHE_REVALIDATORS[S]=[a]}else{o.CACHE_REVALIDATORS[S].push(a)}var i=null;if(!v&&window.addEventListener&&p.revalidateOnReconnect){window.addEventListener("online",i=t)}return function(){m=function(){return null};I.current=true;if(n&&o.FOCUS_REVALIDATORS[S]){var e=o.FOCUS_REVALIDATORS[S];var r=e.indexOf(n);if(r>=0){e[r]=e[e.length-1];e.pop()}}if(o.CACHE_REVALIDATORS[S]){var e=o.CACHE_REVALIDATORS[S];var r=e.indexOf(a);if(r>=0){e[r]=e[e.length-1];e.pop()}}if(!v&&window.removeEventListener&&i!==null){window.removeEventListener("online",i)}}},[S,P]);h(function(){var r=null;var t=function(){return n(e,void 0,void 0,function(){return a(this,function(e){switch(e.label){case 0:if(!(!g.current.error&&(p.refreshWhenHidden||s.default())&&(p.refreshWhenOffline||l.default())))return[3,2];return[4,P({dedupe:true})];case 1:e.sent();e.label=2;case 2:if(p.refreshInterval){r=setTimeout(t,p.refreshInterval)}return[2]}})})};if(p.refreshInterval){r=setTimeout(t,p.refreshInterval)}return function(){if(r)clearTimeout(r)}},[p.refreshInterval,p.refreshWhenHidden,p.refreshWhenOffline,P]);if(p.suspense){var U=o.cache.get(S);var V=o.cache.get(C);if(typeof U==="undefined"&&typeof V==="undefined"){if(!o.CONCURRENT_PROMISES[S]){P()}if(o.CONCURRENT_PROMISES[S]&&typeof o.CONCURRENT_PROMISES[S].then==="function"){throw o.CONCURRENT_PROMISES[S]}U=o.CONCURRENT_PROMISES[S]}if(typeof U==="undefined"&&V){throw V}return{error:V,data:U,revalidate:P,mutate:N,isValidating:g.current.isValidating}}return f.useMemo(function(){var e={revalidate:P,mutate:N};Object.defineProperties(e,{error:{get:function(){b.current.error=true;return M.current===S?g.current.error:T},enumerable:true},data:{get:function(){b.current.data=true;return M.current===S?g.current.data:E},enumerable:true},isValidating:{get:function(){b.current.isValidating=true;return g.current.isValidating},enumerable:true}});return e},[P])}var O=d.default.Provider;r.SWRConfig=O;r.default=useSWR},542:function(e,r){"use strict";Object.defineProperty(r,"__esModule",{value:true});function throttle(e,r){var t=false;return function(){var n=[];for(var a=0;a<arguments.length;a++){n[a]=arguments[a]}if(t)return;t=true;e.apply(void 0,n);setTimeout(function(){return t=false},r)}}r.default=throttle},641:function(e,r,t){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:true});var a=n(t(832));var i=n(t(459));var u=n(t(205));var f=n(t(722));var o=new f.default;r.cache=o;var s={};r.CONCURRENT_PROMISES=s;var l={};r.CONCURRENT_PROMISES_TS=l;var c={};r.FOCUS_REVALIDATORS=c;var d={};r.CACHE_REVALIDATORS=d;var v={};r.MUTATION_TS=v;function onErrorRetry(e,r,t,n,a){if(!i.default()){return}if(t.errorRetryCount&&a.retryCount>t.errorRetryCount){return}var u=Math.min(a.retryCount||0,8);var f=~~((Math.random()+.5)*(1<<u))*t.errorRetryInterval;setTimeout(n,f,a)}var h=typeof window!=="undefined"&&navigator["connection"]&&["slow-2g","2g"].indexOf(navigator["connection"].effectiveType)!==-1;var p={onLoadingSlow:function(){},onSuccess:function(){},onError:function(){},onErrorRetry:onErrorRetry,errorRetryInterval:(h?10:5)*1e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:(h?5:3)*1e3,refreshInterval:0,revalidateOnFocus:true,revalidateOnReconnect:true,refreshWhenHidden:false,refreshWhenOffline:false,shouldRetryOnError:true,suspense:false,compare:a.default};var _=false;if(typeof window!=="undefined"&&window.addEventListener&&!_){var R=function(){if(!i.default()||!u.default())return;for(var e in c){if(c[e][0])c[e][0]()}};window.addEventListener("visibilitychange",R,false);window.addEventListener("focus",R,false);_=true}r.default=p},722:function(e,r,t){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:true});var a=t(516);var i=n(t(202));var u=function(){function Cache(e){if(e===void 0){e={}}this.__cache=new Map(Object.entries(e));this.__listeners=[]}Cache.prototype.get=function(e){var r=this.serializeKey(e)[0];return this.__cache.get(r)};Cache.prototype.set=function(e,r,t){if(t===void 0){t=true}var n=this.serializeKey(e)[0];this.__cache.set(n,r);if(t)a.mutate(e,r,false);this.notify()};Cache.prototype.keys=function(){return Array.from(this.__cache.keys())};Cache.prototype.has=function(e){var r=this.serializeKey(e)[0];return this.__cache.has(r)};Cache.prototype.clear=function(e){if(e===void 0){e=true}if(e)this.__cache.forEach(function(e){return a.mutate(e,null,false)});this.__cache.clear();this.notify()};Cache.prototype.delete=function(e,r){if(r===void 0){r=true}var t=this.serializeKey(e)[0];if(r)a.mutate(e,null,false);this.__cache.delete(t);this.notify()};Cache.prototype.serializeKey=function(e){var r=null;if(typeof e==="function"){try{e=e()}catch(r){e=""}}if(Array.isArray(e)){r=e;e=i.default(e)}else{e=String(e||"")}var t=e?"err@"+e:"";return[e,r,t]};Cache.prototype.subscribe=function(e){var r=this;if(typeof e!=="function"){throw new Error("Expected the listener to be a function.")}var t=true;this.__listeners.push(e);return function(){if(!t)return;t=false;var n=r.__listeners.indexOf(e);if(n>-1){r.__listeners[n]=r.__listeners[r.__listeners.length-1];r.__listeners.length--}}};Cache.prototype.notify=function(){for(var e=0,r=this.__listeners;e<r.length;e++){var t=r[e];t()}};return Cache}();r.default=u},832:function(e){"use strict";var r=Array.isArray;var t=Object.keys;var n=Object.prototype.hasOwnProperty;e.exports=function equal(e,a){if(e===a)return true;if(e&&a&&typeof e=="object"&&typeof a=="object"){var i=r(e),u=r(a),f,o,s;if(i&&u){o=e.length;if(o!=a.length)return false;for(f=o;f--!==0;)if(!equal(e[f],a[f]))return false;return true}if(i!=u)return false;var l=e instanceof Date,c=a instanceof Date;if(l!=c)return false;if(l&&c)return e.getTime()==a.getTime();var d=e instanceof RegExp,v=a instanceof RegExp;if(d!=v)return false;if(d&&v)return e.toString()==a.toString();var h=t(e);o=h.length;if(o!==t(a).length)return false;for(f=o;f--!==0;)if(!n.call(a,h[f]))return false;for(f=o;f--!==0;){s=h[f];if(!equal(e[s],a[s]))return false}return true}return e!==e&&a!==a}},926:function(e,r,t){"use strict";var n=this&&this.__spreadArrays||function(){for(var e=0,r=0,t=arguments.length;r<t;r++)e+=arguments[r].length;for(var n=Array(e),a=0,r=0;r<t;r++)for(var i=arguments[r],u=0,f=i.length;u<f;u++,a++)n[a]=i[u];return n};var a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var t in e)if(Object.hasOwnProperty.call(e,t))r[t]=e[t];r["default"]=e;return r};Object.defineProperty(r,"__esModule",{value:true});var i=a(t(297));var u=t(641);var f=new Map;function useSWRPages(e,r,t,a){if(a===void 0){a=[]}var o="_swr_page_count_"+e;var s="_swr_page_offset_"+e;var l=i.useState(u.cache.get(o)||1),c=l[0],d=l[1];var v=i.useState(u.cache.get(s)||[null]),h=v[0],p=v[1];var _=i.useState([]),R=_[0],O=_[1];var S=i.useRef(r);var y=i.useRef(false);var C=i.useCallback(function(e){var r=S.current(e);if(r&&!r.length){y.current=true}else{y.current=false}return r},[]);var E=h[c]===null;var T=c===h.length;var b=E&&c===1&&y.current;var g=i.useCallback(function(){if(T||E)return;d(function(e){u.cache.set(o,e+1);return e+1})},[T||E]);var w=i.useCallback(r,a);S.current=w;var m=i.useMemo(function(){var r=function(e){return function(r){if(!R[e]||R[e].data!==r.data||R[e].error!==r.error||R[e].revalidate!==r.revalidate){setTimeout(function(){O(function(t){var a=n(t);a[e]={data:r.data,error:r.error,revalidate:r.revalidate,isValidating:r.isValidating,mutate:r.mutate};return a});if(typeof r.data!=="undefined"){var a=t(r,e);if(h[e+1]!==a){p(function(r){var t=n(r);t[e+1]=a;u.cache.set(s,t);return t})}}})}return r}};var a=[];if(!f.has(e)){f.set(e,[])}var o=f.get(e);for(var l=0;l<c;++l){if(!o[l]||o[l].offset!==h[l]||o[l].pageFn!==w){o[l]={component:i.default.createElement(C,{key:"page-"+h[l]+"-"+l,offset:h[l],withSWR:r(l)}),pageFn:w,offset:h[l]}}a.push(o[l].component)}return a},[w,c,R,h,e]);return{pages:m,pageCount:c,pageSWRs:R,isLoadingMore:T,isReachingEnd:E,isEmpty:b,loadMore:g}}r.useSWRPages=useSWRPages}});

@@ -32,3 +32,3 @@ export declare type fetcherFn<Data> = (...args: any) => Data | Promise<Data>;

export declare type triggerInterface = (key: keyInterface, shouldRevalidate?: boolean) => void;
declare type mutateCallback<Data = any> = (currentValue: Data) => Promise<Data>;
declare type mutateCallback<Data = any> = (currentValue: Data) => Promise<Data> | Data;
export declare type mutateInterface<Data = any> = (key: keyInterface, data?: Data | Promise<Data> | mutateCallback<Data>, shouldRevalidate?: boolean) => Promise<Data | undefined>;

@@ -35,0 +35,0 @@ export declare type broadcastStateInterface<Data = any, Error = any> = (key: string, data: Data, error?: Error) => void;

import { mutate } from './use-swr';
import hash from './libs/hash';
export default class Cache {
constructor(initialData = {}) {
var Cache = /** @class */ (function () {
function Cache(initialData) {
if (initialData === void 0) { initialData = {}; }
this.__cache = new Map(Object.entries(initialData));
this.__listeners = [];
}
get(key) {
const [_key] = this.serializeKey(key);
Cache.prototype.get = function (key) {
var _key = this.serializeKey(key)[0];
return this.__cache.get(_key);
}
set(key, value, shouldNotify = true) {
const [_key] = this.serializeKey(key);
};
Cache.prototype.set = function (key, value, shouldNotify) {
if (shouldNotify === void 0) { shouldNotify = true; }
var _key = this.serializeKey(key)[0];
this.__cache.set(_key, value);

@@ -18,18 +20,20 @@ if (shouldNotify)

this.notify();
}
keys() {
};
Cache.prototype.keys = function () {
return Array.from(this.__cache.keys());
}
has(key) {
const [_key] = this.serializeKey(key);
};
Cache.prototype.has = function (key) {
var _key = this.serializeKey(key)[0];
return this.__cache.has(_key);
}
clear(shouldNotify = true) {
};
Cache.prototype.clear = function (shouldNotify) {
if (shouldNotify === void 0) { shouldNotify = true; }
if (shouldNotify)
this.__cache.forEach(key => mutate(key, null, false));
this.__cache.forEach(function (key) { return mutate(key, null, false); });
this.__cache.clear();
this.notify();
}
delete(key, shouldNotify = true) {
const [_key] = this.serializeKey(key);
};
Cache.prototype.delete = function (key, shouldNotify) {
if (shouldNotify === void 0) { shouldNotify = true; }
var _key = this.serializeKey(key)[0];
if (shouldNotify)

@@ -39,6 +43,6 @@ mutate(key, null, false);

this.notify();
}
};
// TODO: introduce namespace for the cache
serializeKey(key) {
let args = null;
Cache.prototype.serializeKey = function (key) {
var args = null;
if (typeof key === 'function') {

@@ -62,28 +66,32 @@ try {

}
const errorKey = key ? 'err@' + key : '';
var errorKey = key ? 'err@' + key : '';
return [key, args, errorKey];
}
subscribe(listener) {
};
Cache.prototype.subscribe = function (listener) {
var _this = this;
if (typeof listener !== 'function') {
throw new Error('Expected the listener to be a function.');
}
let isSubscribed = true;
var isSubscribed = true;
this.__listeners.push(listener);
return () => {
return function () {
if (!isSubscribed)
return;
isSubscribed = false;
const index = this.__listeners.indexOf(listener);
var index = _this.__listeners.indexOf(listener);
if (index > -1) {
this.__listeners[index] = this.__listeners[this.__listeners.length - 1];
this.__listeners.length--;
_this.__listeners[index] = _this.__listeners[_this.__listeners.length - 1];
_this.__listeners.length--;
}
};
}
};
// Notify Cache subscribers about a change in the cache
notify() {
for (let listener of this.__listeners) {
Cache.prototype.notify = function () {
for (var _i = 0, _a = this.__listeners; _i < _a.length; _i++) {
var listener = _a[_i];
listener();
}
}
}
};
return Cache;
}());
export default Cache;

@@ -6,9 +6,9 @@ import deepEqual from 'fast-deep-equal';

// cache
const cache = new Cache();
var cache = new Cache();
// state managers
const CONCURRENT_PROMISES = {};
const CONCURRENT_PROMISES_TS = {};
const FOCUS_REVALIDATORS = {};
const CACHE_REVALIDATORS = {};
const MUTATION_TS = {};
var CONCURRENT_PROMISES = {};
var CONCURRENT_PROMISES_TS = {};
var FOCUS_REVALIDATORS = {};
var CACHE_REVALIDATORS = {};
var MUTATION_TS = {};
// error retry

@@ -25,4 +25,4 @@ function onErrorRetry(_, __, config, revalidate, opts) {

// exponential backoff
const count = Math.min(opts.retryCount || 0, 8);
const timeout = ~~((Math.random() + 0.5) * (1 << count)) * config.errorRetryInterval;
var count = Math.min(opts.retryCount || 0, 8);
var timeout = ~~((Math.random() + 0.5) * (1 << count)) * config.errorRetryInterval;
setTimeout(revalidate, timeout, opts);

@@ -33,12 +33,12 @@ }

// slow connection (<= 70Kbps)
const slowConnection = typeof window !== 'undefined' &&
var slowConnection = typeof window !== 'undefined' &&
navigator['connection'] &&
['slow-2g', '2g'].indexOf(navigator['connection'].effectiveType) !== -1;
// config
const defaultConfig = {
var defaultConfig = {
// events
onLoadingSlow: () => { },
onSuccess: () => { },
onError: () => { },
onErrorRetry,
onLoadingSlow: function () { },
onSuccess: function () { },
onError: function () { },
onErrorRetry: onErrorRetry,
errorRetryInterval: (slowConnection ? 10 : 5) * 1000,

@@ -58,8 +58,8 @@ focusThrottleInterval: 5 * 1000,

// Focus revalidate
let eventsBinded = false;
var eventsBinded = false;
if (typeof window !== 'undefined' && window.addEventListener && !eventsBinded) {
const revalidate = () => {
var revalidate = function () {
if (!isDocumentVisible() || !isOnline())
return;
for (let key in FOCUS_REVALIDATORS) {
for (var key in FOCUS_REVALIDATORS) {
if (FOCUS_REVALIDATORS[key][0])

@@ -66,0 +66,0 @@ FOCUS_REVALIDATORS[key][0]();

@@ -5,5 +5,5 @@ // use WeakMap to store the object->key mapping

// complexity is almost O(1).
const table = new WeakMap();
var table = new WeakMap();
// counter of the key
let counter = 0;
var counter = 0;
// hashes an array of objects and returns a string

@@ -13,5 +13,5 @@ export default function hash(args) {

return '';
let key = 'arg';
for (let i = 0; i < args.length; ++i) {
let _hash;
var key = 'arg';
for (var i = 0; i < args.length; ++i) {
var _hash = void 0;
if (args[i] === null || typeof args[i] !== 'object') {

@@ -18,0 +18,0 @@ // need to consider the case that args[i] is a string:

export default function throttle(fn, interval) {
let pending = false;
return (...args) => {
var pending = false;
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (pending)
return;
pending = true;
fn(...args);
setTimeout(() => (pending = false), interval);
fn.apply(void 0, args);
setTimeout(function () { return (pending = false); }, interval);
};
}
import { createContext } from 'react';
const SWRConfigContext = createContext({});
var SWRConfigContext = createContext({});
SWRConfigContext.displayName = 'SWRConfigContext';
export default SWRConfigContext;

@@ -32,3 +32,3 @@ export declare type fetcherFn<Data> = (...args: any) => Data | Promise<Data>;

export declare type triggerInterface = (key: keyInterface, shouldRevalidate?: boolean) => void;
declare type mutateCallback<Data = any> = (currentValue: Data) => Promise<Data>;
declare type mutateCallback<Data = any> = (currentValue: Data) => Promise<Data> | Data;
export declare type mutateInterface<Data = any> = (key: keyInterface, data?: Data | Promise<Data> | mutateCallback<Data>, shouldRevalidate?: boolean) => Promise<Data | undefined>;

@@ -35,0 +35,0 @@ export declare type broadcastStateInterface<Data = any, Error = any> = (key: string, data: Data, error?: Error) => void;

@@ -0,1 +1,8 @@

var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
import React, { useCallback, useMemo, useState, useRef } from 'react';

@@ -82,16 +89,17 @@ import { cache } from './config';

*/
const pageCacheMap = new Map();
export function useSWRPages(pageKey, pageFn, SWRToOffset, deps = []) {
const pageCountKey = `_swr_page_count_` + pageKey;
const pageOffsetKey = `_swr_page_offset_` + pageKey;
const [pageCount, setPageCount] = useState(cache.get(pageCountKey) || 1);
const [pageOffsets, setPageOffsets] = useState(cache.get(pageOffsetKey) || [null]);
const [pageSWRs, setPageSWRs] = useState([]);
const pageFnRef = useRef(pageFn);
const emptyPageRef = useRef(false);
var pageCacheMap = new Map();
export function useSWRPages(pageKey, pageFn, SWRToOffset, deps) {
if (deps === void 0) { deps = []; }
var pageCountKey = "_swr_page_count_" + pageKey;
var pageOffsetKey = "_swr_page_offset_" + pageKey;
var _a = useState(cache.get(pageCountKey) || 1), pageCount = _a[0], setPageCount = _a[1];
var _b = useState(cache.get(pageOffsetKey) || [null]), pageOffsets = _b[0], setPageOffsets = _b[1];
var _c = useState([]), pageSWRs = _c[0], setPageSWRs = _c[1];
var pageFnRef = useRef(pageFn);
var emptyPageRef = useRef(false);
// Page component (wraps `pageFn`)
// for performance reason we need to memorize it
const Page = useCallback(props => {
var Page = useCallback(function (props) {
// render the page component
const dataList = pageFnRef.current(props);
var dataList = pageFnRef.current(props);
// if dataList is [], we can assume this page is empty

@@ -108,9 +116,9 @@ // TODO: this API is not stable

// Doesn't have a next page
const isReachingEnd = pageOffsets[pageCount] === null;
const isLoadingMore = pageCount === pageOffsets.length;
const isEmpty = isReachingEnd && pageCount === 1 && emptyPageRef.current;
const loadMore = useCallback(() => {
var isReachingEnd = pageOffsets[pageCount] === null;
var isLoadingMore = pageCount === pageOffsets.length;
var isEmpty = isReachingEnd && pageCount === 1 && emptyPageRef.current;
var loadMore = useCallback(function () {
if (isLoadingMore || isReachingEnd)
return;
setPageCount(c => {
setPageCount(function (c) {
cache.set(pageCountKey, c + 1);

@@ -120,6 +128,6 @@ return c + 1;

}, [isLoadingMore || isReachingEnd]);
const _pageFn = useCallback(pageFn, deps);
var _pageFn = useCallback(pageFn, deps);
pageFnRef.current = _pageFn;
const pages = useMemo(() => {
const getWithSWR = id => swr => {
var pages = useMemo(function () {
var getWithSWR = function (id) { return function (swr) {
if (!pageSWRs[id] ||

@@ -130,5 +138,5 @@ pageSWRs[id].data !== swr.data ||

// hoist side effects: setPageSWRs and setPageOffsets -- https://reactjs.org/blog/2020/02/26/react-v16.13.0.html#warnings-for-some-updates-during-render
setTimeout(() => {
setPageSWRs(swrs => {
const _swrs = [...swrs];
setTimeout(function () {
setPageSWRs(function (swrs) {
var _swrs = __spreadArrays(swrs);
_swrs[id] = {

@@ -145,7 +153,7 @@ data: swr.data,

// set next page's offset
const newPageOffset = SWRToOffset(swr, id);
if (pageOffsets[id + 1] !== newPageOffset) {
setPageOffsets(arr => {
const _arr = [...arr];
_arr[id + 1] = newPageOffset;
var newPageOffset_1 = SWRToOffset(swr, id);
if (pageOffsets[id + 1] !== newPageOffset_1) {
setPageOffsets(function (arr) {
var _arr = __spreadArrays(arr);
_arr[id + 1] = newPageOffset_1;
cache.set(pageOffsetKey, _arr);

@@ -159,10 +167,10 @@ return _arr;

return swr;
};
}; };
// render each page
const p = [];
var p = [];
if (!pageCacheMap.has(pageKey)) {
pageCacheMap.set(pageKey, []);
}
const pageCache = pageCacheMap.get(pageKey);
for (let i = 0; i < pageCount; ++i) {
var pageCache = pageCacheMap.get(pageKey);
for (var i = 0; i < pageCount; ++i) {
if (!pageCache[i] ||

@@ -174,3 +182,3 @@ pageCache[i].offset !== pageOffsets[i] ||

pageCache[i] = {
component: (React.createElement(Page, { key: `page-${pageOffsets[i]}-${i}`, offset: pageOffsets[i], withSWR: getWithSWR(i) })),
component: (React.createElement(Page, { key: "page-" + pageOffsets[i] + "-" + i, offset: pageOffsets[i], withSWR: getWithSWR(i) })),
pageFn: _pageFn,

@@ -185,10 +193,10 @@ offset: pageOffsets[i]

return {
pages,
pageCount,
pageSWRs,
isLoadingMore,
isReachingEnd,
isEmpty,
loadMore
pages: pages,
pageCount: pageCount,
pageSWRs: pageSWRs,
isLoadingMore: isLoadingMore,
isReachingEnd: isReachingEnd,
isEmpty: isEmpty,
loadMore: loadMore
};
}

@@ -0,1 +1,37 @@

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { useCallback, useContext, useEffect, useLayoutEffect, useState, useRef, useMemo } from 'react';

@@ -7,18 +43,19 @@ import defaultConfig, { CACHE_REVALIDATORS, CONCURRENT_PROMISES, CONCURRENT_PROMISES_TS, FOCUS_REVALIDATORS, MUTATION_TS, cache } from './config';

import SWRConfigContext from './swr-config-context';
const IS_SERVER = typeof window === 'undefined';
var IS_SERVER = typeof window === 'undefined';
// 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.
const useIsomorphicLayoutEffect = IS_SERVER ? useEffect : useLayoutEffect;
const trigger = (_key, shouldRevalidate = true) => {
var useIsomorphicLayoutEffect = IS_SERVER ? useEffect : useLayoutEffect;
var trigger = function (_key, shouldRevalidate) {
if (shouldRevalidate === void 0) { shouldRevalidate = true; }
// we are ignoring the second argument which correspond to the arguments
// the fetcher will receive when key is an array
const [key, , keyErr] = cache.serializeKey(_key);
var _a = cache.serializeKey(_key), key = _a[0], keyErr = _a[2];
if (!key)
return;
const updaters = CACHE_REVALIDATORS[key];
var updaters = CACHE_REVALIDATORS[key];
if (key && updaters) {
const currentData = cache.get(key);
const currentError = cache.get(keyErr);
for (let i = 0; i < updaters.length; ++i) {
var currentData = cache.get(key);
var currentError = cache.get(keyErr);
for (var i = 0; i < updaters.length; ++i) {
updaters[i](shouldRevalidate, currentData, currentError, i > 0);

@@ -28,6 +65,6 @@ }

};
const broadcastState = (key, data, error) => {
const updaters = CACHE_REVALIDATORS[key];
var broadcastState = function (key, data, error) {
var updaters = CACHE_REVALIDATORS[key];
if (key && updaters) {
for (let i = 0; i < updaters.length; ++i) {
for (var i = 0; i < updaters.length; ++i) {
updaters[i](false, data, error);

@@ -37,51 +74,84 @@ }

};
const mutate = async (_key, _data, shouldRevalidate = true) => {
const [key] = cache.serializeKey(_key);
if (!key)
return;
// if there is no new data, call revalidate against the key
if (typeof _data === 'undefined')
return trigger(_key, shouldRevalidate);
// update timestamp
MUTATION_TS[key] = Date.now() - 1;
let data, error;
if (_data && typeof _data === 'function') {
// `_data` is a function, call it passing current cache value
try {
data = await _data(cache.get(key));
}
catch (err) {
error = err;
}
var mutate = function (_key, _data, shouldRevalidate) {
if (shouldRevalidate === void 0) { shouldRevalidate = true; }
return __awaiter(void 0, void 0, void 0, function () {
var key, data, error, beforeMutationTs, beforeConcurrentPromisesTs, err_1, err_2, updaters, i;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
key = cache.serializeKey(_key)[0];
if (!key)
return [2 /*return*/];
// if there is no new data, call revalidate against the key
if (typeof _data === 'undefined')
return [2 /*return*/, trigger(_key, shouldRevalidate)
// update timestamp
];
// update timestamp
MUTATION_TS[key] = Date.now() - 1;
beforeMutationTs = MUTATION_TS[key];
beforeConcurrentPromisesTs = CONCURRENT_PROMISES_TS[key];
if (!(_data && typeof _data === 'function')) return [3 /*break*/, 5];
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, _data(cache.get(key))];
case 2:
data = _a.sent();
return [3 /*break*/, 4];
case 3:
err_1 = _a.sent();
error = err_1;
return [3 /*break*/, 4];
case 4: return [3 /*break*/, 11];
case 5:
if (!(_data && typeof _data.then === 'function')) return [3 /*break*/, 10];
_a.label = 6;
case 6:
_a.trys.push([6, 8, , 9]);
return [4 /*yield*/, _data];
case 7:
data = _a.sent();
return [3 /*break*/, 9];
case 8:
err_2 = _a.sent();
error = err_2;
return [3 /*break*/, 9];
case 9: return [3 /*break*/, 11];
case 10:
data = _data;
_a.label = 11;
case 11:
// Check if other mutations have occurred since we've started awaiting, if so then do not persist this change
if (beforeMutationTs !== MUTATION_TS[key] ||
beforeConcurrentPromisesTs !== CONCURRENT_PROMISES_TS[key]) {
if (error)
throw error;
return [2 /*return*/, data];
}
if (typeof data !== 'undefined') {
// update cached data, avoid notifying from the cache
cache.set(key, data, false);
}
updaters = CACHE_REVALIDATORS[key];
if (updaters) {
for (i = 0; i < updaters.length; ++i) {
updaters[i](!!shouldRevalidate, data, error, i > 0);
}
}
// throw error or return data to be used by caller of mutate
if (error)
throw error;
return [2 /*return*/, data];
}
});
});
};
function useSWR() {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
else if (_data && typeof _data.then === 'function') {
// `_data` is a promise
try {
data = await _data;
}
catch (err) {
error = err;
}
}
else {
data = _data;
}
if (typeof data !== 'undefined') {
// update cached data, avoid notifying from the cache
cache.set(key, data, false);
}
// update existing SWR Hooks' state
const updaters = CACHE_REVALIDATORS[key];
if (updaters) {
for (let i = 0; i < updaters.length; ++i) {
updaters[i](!!shouldRevalidate, data, error, i > 0);
}
}
// throw error or return data to be used by caller of mutate
if (error)
throw error;
return data;
};
function useSWR(...args) {
let _key, fn, config = {};
var _key, fn, config = {};
if (args.length >= 1) {

@@ -106,3 +176,3 @@ _key = args[0];

// `keyErr` is the cache key for error objects
const [key, fnArgs, keyErr] = cache.serializeKey(_key);
var _a = cache.serializeKey(_key), key = _a[0], fnArgs = _a[1], keyErr = _a[2];
config = Object.assign({}, defaultConfig, useContext(SWRConfigContext), config);

@@ -113,8 +183,8 @@ if (typeof fn === 'undefined') {

}
const initialData = cache.get(key) || config.initialData;
const initialError = cache.get(keyErr);
var initialData = cache.get(key) || config.initialData;
var initialError = cache.get(keyErr);
// if a state is accessed (data, error or isValidating),
// we add the state to dependencies so if the state is
// updated in the future, we can trigger a rerender
const stateDependencies = useRef({
var stateDependencies = useRef({
data: false,

@@ -124,3 +194,3 @@ error: false,

});
const stateRef = useRef({
var stateRef = useRef({
data: initialData,

@@ -130,6 +200,6 @@ error: initialError,

});
const rerender = useState(null)[1];
let dispatch = useCallback(payload => {
let shouldUpdateState = false;
for (let k in payload) {
var rerender = useState(null)[1];
var dispatch = useCallback(function (payload) {
var shouldUpdateState = false;
for (var k in payload) {
stateRef.current[k] = payload[k];

@@ -145,126 +215,153 @@ if (stateDependencies.current[k]) {

// error ref inside revalidate (is last request errored?)
const unmountedRef = useRef(false);
const keyRef = useRef(key);
const boundMutate = useCallback((data, shouldRevalidate) => {
var unmountedRef = useRef(false);
var keyRef = useRef(key);
// do unmount check for callbacks
var eventsRef = useRef({
emit: function (event) {
var params = [];
for (var _i = 1; _i < arguments.length; _i++) {
params[_i - 1] = arguments[_i];
}
if (unmountedRef.current)
return;
config[event].apply(config, params);
}
});
var boundMutate = useCallback(function (data, shouldRevalidate) {
return mutate(key, data, shouldRevalidate);
}, [key]);
// start a revalidation
const revalidate = useCallback(async (revalidateOpts = {}) => {
if (!key || !fn)
return false;
if (unmountedRef.current)
return false;
revalidateOpts = Object.assign({ dedupe: false }, revalidateOpts);
let loading = true;
let shouldDeduping = typeof CONCURRENT_PROMISES[key] !== 'undefined' && revalidateOpts.dedupe;
// start fetching
try {
dispatch({
isValidating: true
var revalidate = useCallback(function (revalidateOpts) {
if (revalidateOpts === void 0) { revalidateOpts = {}; }
return __awaiter(_this, void 0, void 0, function () {
var loading, shouldDeduping, newData, startAt, newState, err_3, retryCount;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!key || !fn)
return [2 /*return*/, false];
if (unmountedRef.current)
return [2 /*return*/, false];
revalidateOpts = Object.assign({ dedupe: false }, revalidateOpts);
loading = true;
shouldDeduping = typeof CONCURRENT_PROMISES[key] !== 'undefined' && revalidateOpts.dedupe;
_a.label = 1;
case 1:
_a.trys.push([1, 6, , 7]);
dispatch({
isValidating: true
});
newData = void 0;
startAt = void 0;
if (!shouldDeduping) return [3 /*break*/, 3];
// there's already an ongoing request,
// this one needs to be deduplicated.
startAt = CONCURRENT_PROMISES_TS[key];
return [4 /*yield*/, CONCURRENT_PROMISES[key]];
case 2:
newData = _a.sent();
return [3 /*break*/, 5];
case 3:
// if not deduping the request (hard revalidate) but
// there're other ongoing request(s) at the same time,
// we need to ignore the other result(s) to avoid
// possible race conditions:
// req1------------------>res1
// req2-------->res2
// in that case, the second response should not be overridden
// by the first one.
if (CONCURRENT_PROMISES[key]) {
// we can mark it as a mutation to ignore
// all requests which are fired before this one
MUTATION_TS[key] = Date.now() - 1;
}
// if no cache being rendered currently (it shows a blank page),
// we trigger the loading slow event.
if (config.loadingTimeout && !cache.get(key)) {
setTimeout(function () {
if (loading)
eventsRef.current.emit('onLoadingSlow', key, config);
}, config.loadingTimeout);
}
if (fnArgs !== null) {
CONCURRENT_PROMISES[key] = fn.apply(void 0, fnArgs);
}
else {
CONCURRENT_PROMISES[key] = fn(key);
}
CONCURRENT_PROMISES_TS[key] = startAt = Date.now();
return [4 /*yield*/, CONCURRENT_PROMISES[key]];
case 4:
newData = _a.sent();
setTimeout(function () {
delete CONCURRENT_PROMISES[key];
delete CONCURRENT_PROMISES_TS[key];
}, config.dedupingInterval);
// trigger the success event,
// only do this for the original request.
eventsRef.current.emit('onSuccess', newData, key, config);
_a.label = 5;
case 5:
// if the revalidation happened earlier than the local mutation,
// we have to ignore the result because it could override.
// meanwhile, a new revalidation should be triggered by the mutation.
if (MUTATION_TS[key] && startAt <= MUTATION_TS[key]) {
dispatch({ isValidating: false });
return [2 /*return*/, false];
}
cache.set(key, newData, false);
cache.set(keyErr, undefined, false);
newState = {
isValidating: false
};
if (typeof stateRef.current.error !== 'undefined') {
// we don't have an error
newState.error = undefined;
}
if (!config.compare(stateRef.current.data, newData)) {
// deep compare to avoid extra re-render
// data changed
newState.data = newData;
}
// merge the new state
dispatch(newState);
if (!shouldDeduping) {
// also update other hooks
broadcastState(key, newData, undefined);
}
return [3 /*break*/, 7];
case 6:
err_3 = _a.sent();
delete CONCURRENT_PROMISES[key];
delete CONCURRENT_PROMISES_TS[key];
cache.set(keyErr, err_3, false);
// get a new error
// don't use deep equal for errors
if (stateRef.current.error !== err_3) {
// we keep the stale data
dispatch({
isValidating: false,
error: err_3
});
if (!shouldDeduping) {
// also broadcast to update other hooks
broadcastState(key, undefined, err_3);
}
}
// events and retry
eventsRef.current.emit('onError', err_3, key, config);
if (config.shouldRetryOnError) {
retryCount = (revalidateOpts.retryCount || 0) + 1;
eventsRef.current.emit('onErrorRetry', err_3, key, config, revalidate, Object.assign({ dedupe: true }, revalidateOpts, { retryCount: retryCount }));
}
return [3 /*break*/, 7];
case 7:
loading = false;
return [2 /*return*/, true];
}
});
let newData;
let startAt;
if (shouldDeduping) {
// there's already an ongoing request,
// this one needs to be deduplicated.
startAt = CONCURRENT_PROMISES_TS[key];
newData = await CONCURRENT_PROMISES[key];
}
else {
// if not deduping the request (hard revalidate) but
// there're other ongoing request(s) at the same time,
// we need to ignore the other result(s) to avoid
// possible race conditions:
// req1------------------>res1
// req2-------->res2
// in that case, the second response should not be overridden
// by the first one.
if (CONCURRENT_PROMISES[key]) {
// we can mark it as a mutation to ignore
// all requests which are fired before this one
MUTATION_TS[key] = Date.now() - 1;
}
// if no cache being rendered currently (it shows a blank page),
// we trigger the loading slow event.
if (config.loadingTimeout && !cache.get(key)) {
setTimeout(() => {
if (loading)
config.onLoadingSlow(key, config);
}, config.loadingTimeout);
}
if (fnArgs !== null) {
CONCURRENT_PROMISES[key] = fn(...fnArgs);
}
else {
CONCURRENT_PROMISES[key] = fn(key);
}
CONCURRENT_PROMISES_TS[key] = startAt = Date.now();
newData = await CONCURRENT_PROMISES[key];
setTimeout(() => {
delete CONCURRENT_PROMISES[key];
delete CONCURRENT_PROMISES_TS[key];
}, config.dedupingInterval);
// trigger the success event,
// only do this for the original request.
config.onSuccess(newData, key, config);
}
// if the revalidation happened earlier than the local mutation,
// we have to ignore the result because it could override.
// meanwhile, a new revalidation should be triggered by the mutation.
if (MUTATION_TS[key] && startAt <= MUTATION_TS[key]) {
dispatch({ isValidating: false });
return false;
}
cache.set(key, newData, false);
cache.set(keyErr, undefined, false);
// new state for the reducer
const newState = {
isValidating: false
};
if (typeof stateRef.current.error !== 'undefined') {
// we don't have an error
newState.error = undefined;
}
if (!config.compare(stateRef.current.data, newData)) {
// deep compare to avoid extra re-render
// data changed
newState.data = newData;
}
// merge the new state
dispatch(newState);
if (!shouldDeduping) {
// also update other hooks
broadcastState(key, newData, undefined);
}
}
catch (err) {
delete CONCURRENT_PROMISES[key];
delete CONCURRENT_PROMISES_TS[key];
cache.set(keyErr, err, false);
// get a new error
// don't use deep equal for errors
if (stateRef.current.error !== err) {
// we keep the stale data
dispatch({
isValidating: false,
error: err
});
if (!shouldDeduping) {
// also broadcast to update other hooks
broadcastState(key, undefined, err);
}
}
// events and retry
config.onError(err, key, config);
if (config.shouldRetryOnError) {
// when retrying, we always enable deduping
const retryCount = (revalidateOpts.retryCount || 0) + 1;
config.onErrorRetry(err, key, config, revalidate, Object.assign({ dedupe: true }, revalidateOpts, { retryCount }));
}
}
loading = false;
return true;
});
}, [key]);
// mounted (client side rendering)
useIsomorphicLayoutEffect(() => {
useIsomorphicLayoutEffect(function () {
if (!key)

@@ -277,4 +374,4 @@ return undefined;

// and trigger a revalidation
const currentHookData = stateRef.current.data;
const latestKeyedData = cache.get(key) || config.initialData;
var currentHookData = stateRef.current.data;
var latestKeyedData = cache.get(key) || config.initialData;
// update the state if the key changed (not the inital render) or cache updated

@@ -287,3 +384,3 @@ if (keyRef.current !== key ||

// revalidate with deduping
const softRevalidate = () => revalidate({ dedupe: true });
var softRevalidate = function () { return revalidate({ dedupe: true }); };
// trigger a revalidation

@@ -304,3 +401,3 @@ if (config.revalidateOnMount ||

// whenever the window gets focused, revalidate
let onFocus;
var onFocus;
if (config.revalidateOnFocus) {

@@ -318,6 +415,8 @@ // throttle: avoid being called twice from both listeners

// register global cache update listener
const onUpdate = (shouldRevalidate = true, updatedData, updatedError, dedupe = true) => {
var onUpdate = function (shouldRevalidate, updatedData, updatedError, dedupe) {
if (shouldRevalidate === void 0) { shouldRevalidate = true; }
if (dedupe === void 0) { dedupe = true; }
// update hook state
const newState = {};
let needUpdate = false;
var newState = {};
var needUpdate = false;
if (typeof updatedData !== 'undefined' &&

@@ -355,14 +454,14 @@ !config.compare(stateRef.current.data, updatedData)) {

// set up reconnecting when the browser regains network connection
let reconnect = null;
var reconnect = null;
if (!IS_SERVER && window.addEventListener && config.revalidateOnReconnect) {
window.addEventListener('online', (reconnect = softRevalidate));
}
return () => {
return function () {
// cleanup
dispatch = () => null;
dispatch = function () { return null; };
// mark it as unmounted
unmountedRef.current = true;
if (onFocus && FOCUS_REVALIDATORS[key]) {
const revalidators = FOCUS_REVALIDATORS[key];
const index = revalidators.indexOf(onFocus);
var revalidators = FOCUS_REVALIDATORS[key];
var index = revalidators.indexOf(onFocus);
if (index >= 0) {

@@ -376,4 +475,4 @@ // 10x faster than splice

if (CACHE_REVALIDATORS[key]) {
const revalidators = CACHE_REVALIDATORS[key];
const index = revalidators.indexOf(onUpdate);
var revalidators = CACHE_REVALIDATORS[key];
var index = revalidators.indexOf(onUpdate);
if (index >= 0) {

@@ -390,21 +489,33 @@ revalidators[index] = revalidators[revalidators.length - 1];

// set up polling
useIsomorphicLayoutEffect(() => {
let timer = null;
const tick = async () => {
if (!stateRef.current.error &&
(config.refreshWhenHidden || isDocumentVisible()) &&
(config.refreshWhenOffline || isOnline())) {
// only revalidate when the page is visible
// if API request errored, we stop polling in this round
// and let the error retry function handle it
await revalidate({ dedupe: true });
}
if (config.refreshInterval) {
timer = setTimeout(tick, config.refreshInterval);
}
};
useIsomorphicLayoutEffect(function () {
var timer = null;
var tick = function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(!stateRef.current.error &&
(config.refreshWhenHidden || isDocumentVisible()) &&
(config.refreshWhenOffline || isOnline()))) return [3 /*break*/, 2];
// only revalidate when the page is visible
// if API request errored, we stop polling in this round
// and let the error retry function handle it
return [4 /*yield*/, revalidate({ dedupe: true })];
case 1:
// only revalidate when the page is visible
// if API request errored, we stop polling in this round
// and let the error retry function handle it
_a.sent();
_a.label = 2;
case 2:
if (config.refreshInterval) {
timer = setTimeout(tick, config.refreshInterval);
}
return [2 /*return*/];
}
});
}); };
if (config.refreshInterval) {
timer = setTimeout(tick, config.refreshInterval);
}
return () => {
return function () {
if (timer)

@@ -424,4 +535,4 @@ clearTimeout(timer);

// try to get data and error from cache
let latestData = cache.get(key);
let latestError = cache.get(keyErr);
var latestData = cache.get(key);
var latestError = cache.get(keyErr);
if (typeof latestData === 'undefined' &&

@@ -452,3 +563,3 @@ typeof latestError === 'undefined') {

data: latestData,
revalidate,
revalidate: revalidate,
mutate: boundMutate,

@@ -460,4 +571,4 @@ isValidating: stateRef.current.isValidating

// can be memorized since the state is a ref
return useMemo(() => {
const state = { revalidate, mutate: boundMutate };
return useMemo(function () {
var state = { revalidate: revalidate, mutate: boundMutate };
Object.defineProperties(state, {

@@ -471,3 +582,4 @@ error: {

return keyRef.current === key ? stateRef.current.error : initialError;
}
},
enumerable: true
},

@@ -478,3 +590,4 @@ data: {

return keyRef.current === key ? stateRef.current.data : initialData;
}
},
enumerable: true
},

@@ -485,3 +598,4 @@ isValidating: {

return stateRef.current.isValidating;
}
},
enumerable: true
}

@@ -492,4 +606,4 @@ });

}
const SWRConfig = SWRConfigContext.Provider;
var SWRConfig = SWRConfigContext.Provider;
export { trigger, mutate, SWRConfig };
export default useSWR;
{
"name": "swr",
"version": "0.2.2",
"version": "0.2.3-beta.0",
"description": "React Hooks library for remote data fetching",

@@ -20,3 +20,3 @@ "main": "./dist/index.js",

"build:cjs": "ncc build src/index.ts -o dist -m -e react",
"build:esm": "tsc --target ESNext --module ES6 --outDir esm",
"build:esm": "tsc --module ES6 --outDir esm",
"watch": "tsc --watch",

@@ -23,0 +23,0 @@ "types:check": "tsc --noEmit",

@@ -383,5 +383,5 @@ [![SWR](https://assets.vercel.com/image/upload/v1572289618/swr/banner.png)](https://swr.now.sh)

Most probably, you need to data mutate used to update the cache when you passed a promise or async function.
Most probably, you need some data to update the cache. The data is resolved or returned from the promise or async function you passed to `mutate`.
The function will returns the updated document, or throw an error, everytime you call it.
The function will return an updated document to let `mutate` update the corresponding cache value. It could throw an error somehow, every time when you call it.

@@ -388,0 +388,0 @@ ```js

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