Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

swr

Package Overview
Dependencies
Maintainers
53
Versions
162
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.1.12 to 0.1.13-beta.0

2

dist/index.js

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

module.exports=function(e,t){"use strict";var n={};function __webpack_require__(t){if(n[t]){return n[t].exports}var r=n[t]={i:t,l:false,exports:{}};e[t].call(r.exports,r,r.exports,__webpack_require__);r.l=true;return r.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});const n=new WeakMap;let r=0;function hash(e){let t="arg";for(let u=0;u<e.length;++u){let i;if(typeof e[u]!=="object"){i=String(e[u])}else{if(!n.has(e[u])){i=r;n.set(e[u],r++)}else{i=n.get(e[u])}}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,n){"use strict";Object.defineProperty(t,"__esModule",{value:true});const r=n(297);const u=r.createContext({});u.displayName="SWRConfigContext";t.default=u},297:function(e){e.exports=require("react")},325:function(e,t,n){"use strict";function __export(e){for(var n in e)if(!t.hasOwnProperty(n))t[n]=e[n]}var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});__export(n(516));const u=r(n(516));var i=n(926);t.useSWRPages=i.useSWRPages;t.default=u.default},337:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:true});const r=n(297);let u=true;function useHydration(){r.useEffect(()=>{setTimeout(()=>{u=false},1)},[]);return u}t.default=useHydration},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,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};var u=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)if(Object.hasOwnProperty.call(e,n))t[n]=e[n];t["default"]=e;return t};Object.defineProperty(t,"__esModule",{value:true});const i=n(297);const o=r(n(832));const s=u(n(641));const f=r(n(209));const c=r(n(459));const a=r(n(337));const l=r(n(542));const d=r(n(202));const R=typeof window==="undefined";const S=R?i.useEffect:i.useLayoutEffect;const _=e=>e?"err@"+e:"";const p=e=>{let t=null;if(typeof e==="function"){try{e=e()}catch(t){e=""}}if(Array.isArray(e)){t=e;e=d.default(e)}else{e=String(e||"")}return[e,t]};const O=(e,t=true)=>{const[n]=p(e);if(!n)return;const r=s.CACHE_REVALIDATORS[n];if(n&&r){const e=s.cacheGet(n);const u=s.cacheGet(_(n));for(let n=0;n<r.length;++n){r[n](t,e,u)}}};t.trigger=O;const E=(e,t,n)=>{const r=s.CACHE_REVALIDATORS[e];if(e&&r){for(let e=0;e<r.length;++e){r[e](false,t,n)}}};const h=async(e,t,n)=>{const[r]=p(e);if(!r)return;s.MUTATION_TS[r]=Date.now()-1;let u,i;if(t&&typeof t.then==="function"){try{u=await t}catch(e){i=e}}else{u=t;if(typeof n==="undefined"){n=true}}if(typeof u!=="undefined"){s.cacheSet(r,u)}const o=s.CACHE_REVALIDATORS[r];if(o){for(let e=0;e<o.length;++e){o[e](!!n,u,i)}}};t.mutate=h;function mergeState(e,t){return{...e,...t}}function useSWR(...e){let t,n,r={};if(e.length>=1){t=e[0]}if(typeof e[1]==="function"){n=e[1]}else if(typeof e[1]==="object"){r=e[1]}if(typeof e[2]==="object"){r=e[2]}const[u,d]=p(t);const O=_(u);r=Object.assign({},s.default,i.useContext(f.default),r);if(typeof n==="undefined"){n=r.fetcher}const h=r.suspense||!a.default();const C=(h?s.cacheGet(u):undefined)||r.initialData;const T=h?s.cacheGet(O):undefined;let[v,y]=i.useReducer(mergeState,{data:C,error:T,isValidating:false});const I=i.useRef(false);const g=i.useRef(u);const M=i.useRef(C);const A=i.useRef(T);const N=i.useCallback(async(e={})=>{if(!u||!n)return false;if(I.current)return false;e=Object.assign({dedupe:false},e);let t=true;let i=typeof s.CONCURRENT_PROMISES[u]!=="undefined"&&e.dedupe;try{y({isValidating:true});let f;let c;if(i){c=s.CONCURRENT_PROMISES_TS[u];f=await s.CONCURRENT_PROMISES[u]}else{if(r.loadingTimeout&&!s.cacheGet(u)){setTimeout(()=>{if(t)r.onLoadingSlow(u,r)},r.loadingTimeout)}if(d!==null){s.CONCURRENT_PROMISES[u]=n(...d)}else{s.CONCURRENT_PROMISES[u]=n(u)}s.CONCURRENT_PROMISES_TS[u]=c=Date.now();setTimeout(()=>{delete s.CONCURRENT_PROMISES[u];delete s.CONCURRENT_PROMISES_TS[u]},r.dedupingInterval);f=await s.CONCURRENT_PROMISES[u];r.onSuccess(f,u,r)}if(s.MUTATION_TS[u]&&c<=s.MUTATION_TS[u]){y({isValidating:false});return false}s.cacheSet(u,f);s.cacheSet(O,undefined);g.current=u;const a={isValidating:false};if(typeof A.current!=="undefined"){a.error=undefined;A.current=undefined}if(o.default(M.current,f)){}else{a.data=f;M.current=f}y(a);if(!i){E(u,f,undefined)}}catch(t){delete s.CONCURRENT_PROMISES[u];delete s.CONCURRENT_PROMISES_TS[u];s.cacheSet(O,t);g.current=u;if(A.current!==t){A.current=t;y({isValidating:false,error:t});if(!i){E(u,undefined,t)}}r.onError(t,u,r);if(r.shouldRetryOnError){const n=(e.retryCount||0)+1;r.onErrorRetry(t,u,r,N,Object.assign({dedupe:true},e,{retryCount:n}))}}t=false;return true},[u]);S(()=>{if(!u)return undefined;I.current=false;const e=M.current;const t=s.cacheGet(u)||r.initialData;if(g.current!==u||!o.default(e,t)){y({data:t});M.current=t;g.current=u}const n=()=>N({dedupe:true});if(typeof t!=="undefined"&&!R&&window["requestIdleCallback"]){window["requestIdleCallback"](n)}else{n()}let i;if(r.revalidateOnFocus){i=l.default(n,r.focusThrottleInterval);if(!s.FOCUS_REVALIDATORS[u]){s.FOCUS_REVALIDATORS[u]=[i]}else{s.FOCUS_REVALIDATORS[u].push(i)}}const f=(e=true,t,r)=>{const i={};if(typeof t!=="undefined"&&!o.default(M.current,t)){i.data=t;M.current=t}if(A.current!==r){i.error=r;A.current=r}y(i);g.current=u;if(e){return n()}return false};if(!s.CACHE_REVALIDATORS[u]){s.CACHE_REVALIDATORS[u]=[f]}else{s.CACHE_REVALIDATORS[u].push(f)}let a=null;if(r.refreshInterval){const e=async()=>{if(!A.current&&(r.refreshWhenHidden||c.default())){await n()}const t=r.refreshInterval;a=setTimeout(e,t)};a=setTimeout(e,r.refreshInterval)}return()=>{y=(()=>null);I.current=true;if(i&&s.FOCUS_REVALIDATORS[u]){const e=s.FOCUS_REVALIDATORS[u];const t=e.indexOf(i);if(t>=0){e[t]=e[e.length-1];e.pop()}}if(s.CACHE_REVALIDATORS[u]){const e=s.CACHE_REVALIDATORS[u];const t=e.indexOf(f);if(t>=0){e[t]=e[e.length-1];e.pop()}}if(a!==null){clearTimeout(a)}}},[u,r.refreshInterval,N]);if(r.suspense){if(R)throw new Error("Suspense on server side is not yet supported!");let e=s.cacheGet(u);let t=s.cacheGet(O);if(typeof e==="undefined"&&typeof t==="undefined"){if(!s.CONCURRENT_PROMISES[u]){N()}if(s.CONCURRENT_PROMISES[u]&&typeof s.CONCURRENT_PROMISES[u].then==="function"){throw s.CONCURRENT_PROMISES[u]}e=s.CONCURRENT_PROMISES[u]}if(typeof e==="undefined"&&t){throw t}return{error:t,data:e,revalidate:N,isValidating:v.isValidating}}return{error:v.error,data:g.current===u?v.data:undefined,revalidate:N,isValidating:v.isValidating}}const C=f.default.Provider;t.SWRConfig=C;t.default=useSWR},542:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:true});function throttle(e,t){let n=false;return(...r)=>{if(n)return;n=true;e(...r);setTimeout(()=>n=false,t)}}t.default=throttle},641:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const u=r(n(459));const i=r(n(205));const o=new Map;function cacheGet(e){return o.get(e)||undefined}t.cacheGet=cacheGet;function cacheSet(e,t){return o.set(e,t)}t.cacheSet=cacheSet;function cacheClear(){o.clear()}t.cacheClear=cacheClear;const s={};t.CONCURRENT_PROMISES=s;const f={};t.CONCURRENT_PROMISES_TS=f;const c={};t.FOCUS_REVALIDATORS=c;const a={};t.CACHE_REVALIDATORS=a;const l={};t.MUTATION_TS=l;function onErrorRetry(e,t,n,r,i){if(!u.default()){return}const o=Math.min(i.retryCount||0,8);const s=~~((Math.random()+.5)*(1<<o))*n.errorRetryInterval;setTimeout(r,s,i)}const d={onLoadingSlow:()=>{},onSuccess:()=>{},onError:()=>{},onErrorRetry:onErrorRetry,errorRetryInterval:5*1e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:3*1e3,refreshInterval:0,revalidateOnFocus:true,refreshWhenHidden:false,shouldRetryOnError:true,suspense:false};if(typeof window!=="undefined"){if(navigator["connection"]){if(["slow-2g","2g"].indexOf(navigator["connection"].effectiveType)!==-1){d.errorRetryInterval=10*1e3;d.loadingTimeout=5*1e3}}}let R=false;if(typeof window!=="undefined"&&window.addEventListener&&!R){const e=()=>{if(!u.default()||!i.default())return;for(let e in c){if(c[e][0])c[e][0]()}};window.addEventListener("visibilitychange",e,false);window.addEventListener("focus",e,false);R=true}t.default=d},832:function(e){"use strict";var t=Array.isArray;var n=Object.keys;var r=Object.prototype.hasOwnProperty;e.exports=function equal(e,u){if(e===u)return true;if(e&&u&&typeof e=="object"&&typeof u=="object"){var i=t(e),o=t(u),s,f,c;if(i&&o){f=e.length;if(f!=u.length)return false;for(s=f;s--!==0;)if(!equal(e[s],u[s]))return false;return true}if(i!=o)return false;var a=e instanceof Date,l=u instanceof Date;if(a!=l)return false;if(a&&l)return e.getTime()==u.getTime();var d=e instanceof RegExp,R=u instanceof RegExp;if(d!=R)return false;if(d&&R)return e.toString()==u.toString();var S=n(e);f=S.length;if(f!==n(u).length)return false;for(s=f;s--!==0;)if(!r.call(u,S[s]))return false;for(s=f;s--!==0;){c=S[s];if(!equal(e[c],u[c]))return false}return true}return e!==e&&u!==u}},926:function(e,t,n){"use strict";var r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)if(Object.hasOwnProperty.call(e,n))t[n]=e[n];t["default"]=e;return t};Object.defineProperty(t,"__esModule",{value:true});const u=r(n(297));const i=n(641);function useSWRPages(e,t,n,r=[]){const o=`_swr_page_count_`+e;const s=`_swr_page_offset_`+e;const[f,c]=u.useState(i.cacheGet(o)||1);const[a,l]=u.useState(i.cacheGet(s)||[null]);const[d,R]=u.useState([]);const S=u.useRef([]);const _=u.useRef(t);const p=u.useRef(false);const O=u.useCallback(e=>{const t=_.current(e);if(t&&!t.length){p.current=true}else{p.current=false}return t},[]);const E=a[f]===null;const h=f===a.length;const C=E&&f===1&&p.current;const T=u.useCallback(()=>{if(h||E)return;c(e=>{i.cacheSet(o,e+1);return e+1})},[h||E]);const v=u.useCallback(t,r);_.current=v;const y=u.useMemo(()=>{const e=e=>t=>{if(!d[e]||d[e].data!==t.data||d[e].error!==t.error||d[e].revalidate!==t.revalidate){R(n=>{const r=[...n];r[e]=t;return r});if(typeof t.data!=="undefined"){const r=n(t,e);if(a[e+1]!==r){l(t=>{const n=[...t];n[e+1]=r;i.cacheSet(s,n);return n})}}}return t};const t=[];const r=S.current;for(let n=0;n<f;++n){if(!r[n]||r[n].offset!==a[n]||r[n].pageFn!==v){r[n]={component:u.default.createElement(O,{key:`page-${a[n]}-${n}`,offset:a[n],withSWR:e(n)}),pageFn:v,offset:a[n]}}t.push(r[n].component)}return t},[v,f,d,a,e]);return{pages:y,pageCount:f,pageSWRs:d,isLoadingMore:h,isReachingEnd:E,isEmpty:C,loadMore:T}}t.useSWRPages=useSWRPages}});
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});const r=new WeakMap;let n=0;function hash(e){if(!e.length)return"";let t="arg";for(let u=0;u<e.length;++u){let i;if(typeof e[u]!=="object"){if(typeof e[u]==="string"){i='"'+e[u]+'"'}else{i=String(e[u])}}else{if(!r.has(e[u])){i=n;r.set(e[u],n++)}else{i=r.get(e[u])}}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});const n=r(297);const u=n.createContext({});u.displayName="SWRConfigContext";t.default=u},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));const u=n(r(516));var i=r(926);t.useSWRPages=i.useSWRPages;t.default=u.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.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};var u=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});const i=r(297);const o=n(r(832));const f=u(r(641));const s=n(r(209));const c=n(r(459));const a=n(r(542));const l=n(r(202));const d=typeof window==="undefined";const R=d?i.useEffect:i.useLayoutEffect;const S=e=>e?"err@"+e:"";const p=e=>{let t=null;if(typeof e==="function"){try{e=e()}catch(t){e=""}}if(Array.isArray(e)){t=e;e=l.default(e)}else{e=String(e||"")}return[e,t]};const O=(e,t=true)=>{const[r]=p(e);if(!r)return;const n=f.CACHE_REVALIDATORS[r];if(r&&n){const e=f.cacheGet(r);const u=f.cacheGet(S(r));for(let r=0;r<n.length;++r){n[r](t,e,u,true)}}};t.trigger=O;const _=(e,t,r)=>{const n=f.CACHE_REVALIDATORS[e];if(e&&n){for(let e=0;e<n.length;++e){n[e](false,t,r)}}};const E=async(e,t,r)=>{const[n]=p(e);if(!n)return;f.MUTATION_TS[n]=Date.now()-1;let u,i;if(t&&typeof t.then==="function"){try{u=await t}catch(e){i=e}}else{u=t;if(typeof r==="undefined"){r=true}}if(typeof u!=="undefined"){f.cacheSet(n,u)}const o=f.CACHE_REVALIDATORS[n];if(o){for(let e=0;e<o.length;++e){o[e](!!r,u,i,true)}}};t.mutate=E;function useSWR(...e){let t,r,n={};if(e.length>=1){t=e[0]}if(e.length>=2){r=e[1];n=e[2]}else{if(typeof e[1]==="function"){r=e[1]}else if(typeof e[1]==="object"){n=e[1]}}const[u,l]=p(t);const O=S(u);n=Object.assign({},f.default,i.useContext(s.default),n);if(typeof r==="undefined"){r=n.fetcher}const E=f.cacheGet(u)||n.initialData;const C=f.cacheGet(O);const T=i.useRef({data:false,error:false,isValidating:false});const h=i.useRef({data:E,error:C,isValidating:false});const v=i.useState(null)[1];let y=e=>{let t=false;for(let r in e){h.current[r]=e[r];if(T.current[r]){t=true}}if(t||n.suspense){v({})}};const I=i.useRef(false);const M=i.useRef(u);const A=i.useCallback(async(e={})=>{if(!u||!r)return false;if(I.current)return false;e=Object.assign({dedupe:false},e);let t=true;let i=typeof f.CONCURRENT_PROMISES[u]!=="undefined"&&e.dedupe;try{y({isValidating:true});let s;let c;if(i){c=f.CONCURRENT_PROMISES_TS[u];s=await f.CONCURRENT_PROMISES[u]}else{if(f.CONCURRENT_PROMISES[u]){f.MUTATION_TS[u]=Date.now()-1}if(n.loadingTimeout&&!f.cacheGet(u)){setTimeout(()=>{if(t)n.onLoadingSlow(u,n)},n.loadingTimeout)}if(l!==null){f.CONCURRENT_PROMISES[u]=r(...l)}else{f.CONCURRENT_PROMISES[u]=r(u)}f.CONCURRENT_PROMISES_TS[u]=c=Date.now();setTimeout(()=>{delete f.CONCURRENT_PROMISES[u];delete f.CONCURRENT_PROMISES_TS[u]},n.dedupingInterval);s=await f.CONCURRENT_PROMISES[u];n.onSuccess(s,u,n)}if(f.MUTATION_TS[u]&&c<=f.MUTATION_TS[u]){y({isValidating:false});return false}f.cacheSet(u,s);f.cacheSet(O,undefined);M.current=u;const a={isValidating:false};if(typeof h.current.error!=="undefined"){a.error=undefined}if(o.default(h.current.data,s)){}else{a.data=s}y(a);if(!i){_(u,s,undefined)}}catch(t){delete f.CONCURRENT_PROMISES[u];delete f.CONCURRENT_PROMISES_TS[u];f.cacheSet(O,t);M.current=u;if(h.current.error!==t){y({isValidating:false,error:t});if(!i){_(u,undefined,t)}}n.onError(t,u,n);if(n.shouldRetryOnError){const r=(e.retryCount||0)+1;n.onErrorRetry(t,u,n,A,Object.assign({dedupe:true},e,{retryCount:r}))}}t=false;return true},[u]);R(()=>{if(!u)return undefined;I.current=false;const e=h.current.data;const t=f.cacheGet(u)||n.initialData;if(M.current!==u||!o.default(e,t)){y({data:t});M.current=u}const r=()=>A({dedupe:true});if(typeof t!=="undefined"&&!d&&window["requestIdleCallback"]){window["requestIdleCallback"](r)}else{r()}let i;if(n.revalidateOnFocus){i=a.default(r,n.focusThrottleInterval);if(!f.FOCUS_REVALIDATORS[u]){f.FOCUS_REVALIDATORS[u]=[i]}else{f.FOCUS_REVALIDATORS[u].push(i)}}const s=(e=true,t,n,i=true)=>{const f={};let s=false;if(typeof t!=="undefined"&&!o.default(h.current.data,t)){f.data=t;s=true}if(h.current.error!==n){f.error=n;s=true}if(s){y(f)}M.current=u;if(e){if(i){return r()}else{return A()}}return false};if(!f.CACHE_REVALIDATORS[u]){f.CACHE_REVALIDATORS[u]=[s]}else{f.CACHE_REVALIDATORS[u].push(s)}let l=null;if(n.refreshInterval){const e=async()=>{if(!h.current.error&&(n.refreshWhenHidden||c.default())){await r()}const t=n.refreshInterval;l=setTimeout(e,t)};l=setTimeout(e,n.refreshInterval)}return()=>{y=(()=>null);I.current=true;if(i&&f.FOCUS_REVALIDATORS[u]){const e=f.FOCUS_REVALIDATORS[u];const t=e.indexOf(i);if(t>=0){e[t]=e[e.length-1];e.pop()}}if(f.CACHE_REVALIDATORS[u]){const e=f.CACHE_REVALIDATORS[u];const t=e.indexOf(s);if(t>=0){e[t]=e[e.length-1];e.pop()}}if(l!==null){clearTimeout(l)}}},[u,n.refreshInterval,A]);if(n.suspense){if(d)throw new Error("Suspense on server side is not yet supported!");let e=f.cacheGet(u);let t=f.cacheGet(O);if(typeof e==="undefined"&&typeof t==="undefined"){if(!f.CONCURRENT_PROMISES[u]){A()}if(f.CONCURRENT_PROMISES[u]&&typeof f.CONCURRENT_PROMISES[u].then==="function"){throw f.CONCURRENT_PROMISES[u]}e=f.CONCURRENT_PROMISES[u]}if(typeof e==="undefined"&&t){throw t}return{error:t,data:e,revalidate:A,isValidating:h.current.isValidating}}const N={revalidate:A};Object.defineProperties(N,{error:{get:function(){T.current.error=true;return M.current===u?h.current.error:C}},data:{get:function(){T.current.data=true;return M.current===u?h.current.data:E}},isValidating:{get:function(){T.current.isValidating=true;return h.current.isValidating}}});return N}const C=s.default.Provider;t.SWRConfig=C;t.default=useSWR},542:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:true});function throttle(e,t){let r=false;return(...n)=>{if(r)return;r=true;e(...n);setTimeout(()=>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});const u=n(r(459));const i=n(r(205));const o=new Map;function cacheGet(e){return o.get(e)}t.cacheGet=cacheGet;function cacheSet(e,t){return o.set(e,t)}t.cacheSet=cacheSet;function cacheClear(){o.clear()}t.cacheClear=cacheClear;const f={};t.CONCURRENT_PROMISES=f;const s={};t.CONCURRENT_PROMISES_TS=s;const c={};t.FOCUS_REVALIDATORS=c;const a={};t.CACHE_REVALIDATORS=a;const l={};t.MUTATION_TS=l;function onErrorRetry(e,t,r,n,i){if(!u.default()){return}const o=Math.min(i.retryCount||0,8);const f=~~((Math.random()+.5)*(1<<o))*r.errorRetryInterval;setTimeout(n,f,i)}const d={onLoadingSlow:()=>{},onSuccess:()=>{},onError:()=>{},onErrorRetry:onErrorRetry,errorRetryInterval:5*1e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:3*1e3,refreshInterval:0,revalidateOnFocus:true,refreshWhenHidden:false,shouldRetryOnError:true,suspense:false};if(typeof window!=="undefined"){if(navigator["connection"]){if(["slow-2g","2g"].indexOf(navigator["connection"].effectiveType)!==-1){d.errorRetryInterval=10*1e3;d.loadingTimeout=5*1e3}}}let R=false;if(typeof window!=="undefined"&&window.addEventListener&&!R){const e=()=>{if(!u.default()||!i.default())return;for(let e in c){if(c[e][0])c[e][0]()}};window.addEventListener("visibilitychange",e,false);window.addEventListener("focus",e,false);R=true}t.default=d},832:function(e){"use strict";var t=Array.isArray;var r=Object.keys;var n=Object.prototype.hasOwnProperty;e.exports=function equal(e,u){if(e===u)return true;if(e&&u&&typeof e=="object"&&typeof u=="object"){var i=t(e),o=t(u),f,s,c;if(i&&o){s=e.length;if(s!=u.length)return false;for(f=s;f--!==0;)if(!equal(e[f],u[f]))return false;return true}if(i!=o)return false;var a=e instanceof Date,l=u instanceof Date;if(a!=l)return false;if(a&&l)return e.getTime()==u.getTime();var d=e instanceof RegExp,R=u instanceof RegExp;if(d!=R)return false;if(d&&R)return e.toString()==u.toString();var S=r(e);s=S.length;if(s!==r(u).length)return false;for(f=s;f--!==0;)if(!n.call(u,S[f]))return false;for(f=s;f--!==0;){c=S[f];if(!equal(e[c],u[c]))return false}return true}return e!==e&&u!==u}},926:function(e,t,r){"use strict";var n=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});const u=n(r(297));const i=r(641);function useSWRPages(e,t,r,n=[]){const o=`_swr_page_count_`+e;const f=`_swr_page_offset_`+e;const[s,c]=u.useState(i.cacheGet(o)||1);const[a,l]=u.useState(i.cacheGet(f)||[null]);const[d,R]=u.useState([]);const S=u.useRef([]);const p=u.useRef(t);const O=u.useRef(false);const _=u.useCallback(e=>{const t=p.current(e);if(t&&!t.length){O.current=true}else{O.current=false}return t},[]);const E=a[s]===null;const C=s===a.length;const T=E&&s===1&&O.current;const h=u.useCallback(()=>{if(C||E)return;c(e=>{i.cacheSet(o,e+1);return e+1})},[C||E]);const v=u.useCallback(t,n);p.current=v;const y=u.useMemo(()=>{const e=e=>t=>{if(!d[e]||d[e].data!==t.data||d[e].error!==t.error||d[e].revalidate!==t.revalidate){R(r=>{const n=[...r];n[e]=t;return n});if(typeof t.data!=="undefined"){const n=r(t,e);if(a[e+1]!==n){l(t=>{const r=[...t];r[e+1]=n;i.cacheSet(f,r);return r})}}}return t};const t=[];const n=S.current;for(let r=0;r<s;++r){if(!n[r]||n[r].offset!==a[r]||n[r].pageFn!==v){n[r]={component:u.default.createElement(_,{key:`page-${a[r]}-${r}`,offset:a[r],withSWR:e(r)}),pageFn:v,offset:a[r]}}t.push(n[r].component)}return t},[v,s,d,a,e]);return{pages:y,pageCount:s,pageSWRs:d,isLoadingMore:C,isReachingEnd:E,isEmpty:T,loadMore:h}}t.useSWRPages=useSWRPages}});

@@ -26,3 +26,3 @@ import { Reducer } from 'react';

export declare type keyInterface = keyFunction | string | any[] | null;
export declare type updaterInterface<Data = any, Error = any> = (shouldRevalidate?: boolean, data?: Data, error?: Error) => boolean | Promise<boolean>;
export declare type updaterInterface<Data = any, Error = any> = (shouldRevalidate?: boolean, data?: Data, error?: Error, shouldDedupe?: boolean) => boolean | Promise<boolean>;
export declare type triggerInterface = (key: keyInterface, shouldRevalidate?: boolean) => void;

@@ -29,0 +29,0 @@ export declare type mutateInterface<Data = any> = (key: keyInterface, data: Data | Promise<Data>, shouldRevalidate?: boolean) => void;

@@ -6,3 +6,3 @@ import isDocumentVisible from './libs/is-document-visible';

function cacheGet(key) {
return __cache.get(key) || undefined;
return __cache.get(key);
}

@@ -9,0 +9,0 @@ function cacheSet(key, value) {

@@ -10,2 +10,4 @@ // use WeakMap to store the object->key mapping

export default function hash(args) {
if (!args.length)
return '';
let key = 'arg';

@@ -15,3 +17,15 @@ for (let i = 0; i < args.length; ++i) {

if (typeof args[i] !== 'object') {
_hash = String(args[i]);
// need to consider the case that args[i] is a string:
// args[i] _hash
// "undefined" -> '"undefined"'
// undefined -> 'undefined'
// 123 -> '123'
// null -> 'null'
// "null" -> '"null"'
if (typeof args[i] === 'string') {
_hash = '"' + args[i] + '"';
}
else {
_hash = String(args[i]);
}
}

@@ -18,0 +32,0 @@ else {

@@ -26,3 +26,3 @@ import { Reducer } from 'react';

export declare type keyInterface = keyFunction | string | any[] | null;
export declare type updaterInterface<Data = any, Error = any> = (shouldRevalidate?: boolean, data?: Data, error?: Error) => boolean | Promise<boolean>;
export declare type updaterInterface<Data = any, Error = any> = (shouldRevalidate?: boolean, data?: Data, error?: Error, shouldDedupe?: boolean) => boolean | Promise<boolean>;
export declare type triggerInterface = (key: keyInterface, shouldRevalidate?: boolean) => void;

@@ -29,0 +29,0 @@ export declare type mutateInterface<Data = any> = (key: keyInterface, data: Data | Promise<Data>, shouldRevalidate?: boolean) => void;

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

import { useEffect, useLayoutEffect, useRef, useContext, useCallback, useReducer } from 'react';
import { useEffect, useLayoutEffect, useRef, useState, useContext, useCallback } from 'react';
import deepEqual from 'fast-deep-equal';

@@ -6,3 +6,2 @@ import defaultConfig, { CONCURRENT_PROMISES, CONCURRENT_PROMISES_TS, FOCUS_REVALIDATORS, CACHE_REVALIDATORS, MUTATION_TS, cacheGet, cacheSet } from './config';

import isDocumentVisible from './libs/is-document-visible';
import useHydration from './libs/use-hydration';
import throttle from './libs/throttle';

@@ -48,3 +47,3 @@ import hash from './libs/hash';

for (let i = 0; i < updaters.length; ++i) {
updaters[i](shouldRevalidate, currentData, currentError);
updaters[i](shouldRevalidate, currentData, currentError, true);
}

@@ -93,9 +92,6 @@ }

for (let i = 0; i < updaters.length; ++i) {
updaters[i](!!shouldRevalidate, data, error);
updaters[i](!!shouldRevalidate, data, error, true);
}
}
};
function mergeState(state, payload) {
return { ...state, ...payload };
}
function useSWR(...args) {

@@ -106,11 +102,14 @@ let _key, fn, config = {};

}
if (typeof args[1] === 'function') {
if (args.length >= 2) {
fn = args[1];
config = args[2];
}
else if (typeof args[1] === 'object') {
config = args[1];
else {
if (typeof args[1] === 'function') {
fn = args[1];
}
else if (typeof args[1] === 'object') {
config = args[1];
}
}
if (typeof args[2] === 'object') {
config = args[2];
}
// we assume `key` as the identifier of the request

@@ -127,8 +126,13 @@ // `key` can change but `fn` shouldn't

}
// it is fine to call `useHydration` conditionally here
// because `config.suspense` should never change
const shouldReadCache = config.suspense || !useHydration();
const initialData = (shouldReadCache ? cacheGet(key) : undefined) || config.initialData;
const initialError = shouldReadCache ? cacheGet(keyErr) : undefined;
let [state, dispatch] = useReducer(mergeState, {
const initialData = cacheGet(key) || config.initialData;
const initialError = cacheGet(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({
data: false,
error: false,
isValidating: false
});
const stateRef = useRef({
data: initialData,

@@ -138,7 +142,18 @@ error: initialError,

});
const rerender = useState(null)[1];
let dispatch = payload => {
let shouldUpdateState = false;
for (let k in payload) {
stateRef.current[k] = payload[k];
if (stateDependencies.current[k]) {
shouldUpdateState = true;
}
}
if (shouldUpdateState || config.suspense) {
rerender({});
}
};
// error ref inside revalidate (is last request errored?)
const unmountedRef = useRef(false);
const keyRef = useRef(key);
const dataRef = useRef(initialData);
const errorRef = useRef(initialError);
// start a revalidation

@@ -167,2 +182,15 @@ const revalidate = useCallback(async (revalidateOpts = {}) => {

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),

@@ -206,8 +234,7 @@ // we trigger the loading slow event.

};
if (typeof errorRef.current !== 'undefined') {
if (typeof stateRef.current.error !== 'undefined') {
// we don't have an error
newState.error = undefined;
errorRef.current = undefined;
}
if (deepEqual(dataRef.current, newData)) {
if (deepEqual(stateRef.current.data, newData)) {
// deep compare to avoid extra re-render

@@ -219,3 +246,2 @@ // do nothing

newState.data = newData;
dataRef.current = newData;
}

@@ -236,4 +262,3 @@ // merge the new state

// don't use deep equal for errors
if (errorRef.current !== err) {
errorRef.current = err;
if (stateRef.current.error !== err) {
// we keep the stale data

@@ -269,3 +294,3 @@ dispatch({

// and trigger a revalidation
const currentHookData = dataRef.current;
const currentHookData = stateRef.current.data;
const latestKeyedData = cacheGet(key) || config.initialData;

@@ -276,3 +301,2 @@ // update the state if the key changed or cache updated

dispatch({ data: latestKeyedData });
dataRef.current = latestKeyedData;
keyRef.current = key;

@@ -307,20 +331,28 @@ }

// register global cache update listener
const onUpdate = (shouldRevalidate = true, updatedData, updatedError) => {
const onUpdate = (shouldRevalidate = true, updatedData, updatedError, dedupe = true) => {
// update hook state
const newState = {};
let needUpdate = false;
if (typeof updatedData !== 'undefined' &&
!deepEqual(dataRef.current, updatedData)) {
!deepEqual(stateRef.current.data, updatedData)) {
newState.data = updatedData;
dataRef.current = updatedData;
needUpdate = true;
}
// always update error
// because it can be `undefined`
if (errorRef.current !== updatedError) {
if (stateRef.current.error !== updatedError) {
newState.error = updatedError;
errorRef.current = updatedError;
needUpdate = true;
}
dispatch(newState);
if (needUpdate) {
dispatch(newState);
}
keyRef.current = key;
if (shouldRevalidate) {
return softRevalidate();
if (dedupe) {
return softRevalidate();
}
else {
return revalidate();
}
}

@@ -340,3 +372,3 @@ return false;

const tick = async () => {
if (!errorRef.current &&
if (!stateRef.current.error &&
(config.refreshWhenHidden || isDocumentVisible())) {

@@ -416,14 +448,31 @@ // only revalidate when the page is visible

revalidate,
isValidating: state.isValidating
isValidating: stateRef.current.isValidating
};
}
return {
error: state.error,
// `key` might be changed in the upcoming hook re-render,
// but the previous state will stay
// so we need to match the latest key and data
data: keyRef.current === key ? state.data : undefined,
revalidate,
isValidating: state.isValidating
};
// define returned state
const state = { revalidate };
Object.defineProperties(state, {
error: {
// `key` might be changed in the upcoming hook re-render,
// but the previous state will stay
// so we need to match the latest key and data (fallback to `initialData`)
get: function () {
stateDependencies.current.error = true;
return keyRef.current === key ? stateRef.current.error : initialError;
}
},
data: {
get: function () {
stateDependencies.current.data = true;
return keyRef.current === key ? stateRef.current.data : initialData;
}
},
isValidating: {
get: function () {
stateDependencies.current.isValidating = true;
return stateRef.current.isValidating;
}
}
});
return state;
}

@@ -430,0 +479,0 @@ const SWRConfig = SWRConfigContext.Provider;

{
"name": "swr",
"version": "0.1.12",
"version": "0.1.13-beta.0",
"description": "React Hooks library for remote data fetching",
"main": "./dist/index.js",
"module": "./esm/index.js",
"react-native": "./esm/index.js",
"types": "./dist/index.d.ts",

@@ -22,5 +23,5 @@ "files": [

"types:check": "tsc --noEmit",
"format": "prettier --write '{src,test,examples}/**/*.{ts,tsx}'",
"lint": "eslint '{src,test,examples}/**/*.{ts,tsx}'",
"lint:fix": "eslint '{src,test,examples}/**/*.{ts,tsx}' --fix",
"format": "prettier --write \"{src,test,examples}/**/*.{ts,tsx}\"",
"lint": "eslint \"{src,test,examples}/**/*.{ts,tsx}\"",
"lint:fix": "eslint \"{src,test,examples}/**/*.{ts,tsx}\" --fix",
"test": "jest"

@@ -63,4 +64,4 @@ },

"peerDependencies": {
"react": "16.11.0"
"react": "^16.11.0"
}
}

@@ -71,3 +71,3 @@ [![SWR](https://assets.zeit.co/image/upload/v1572289618/swr/banner.png)](https://swr.now.sh)

Check out [swr.now.sh](https://swr.now.sh) for more demos of SWR.
Check out [swr.now.sh](https://swr.now.sh) for more demos of SWR, and [Examples](#examples) for the best practices.

@@ -121,4 +121,4 @@ <br/>

- `errorRetryInterval = 5000`: error retry interval [(details)](#error-retries)
- `onLoadingSlow`: callback function when a request takes too long to load (`loadingTimeout`)
- `onSuccess`: callback function when a request finishs successfully
- `onLoadingSlow`: callback function when a request takes too long to load (see `loadingTimeout`)
- `onSuccess`: callback function when a request finishes successfully
- `onError`: callback function when a request returns an error

@@ -142,6 +142,7 @@ - `onErrorRetry`: handler for [error retry](#error-retries)

- [Manually Revalidate](#manually-revalidate)
- [Local Mutation](#local-mutation)
- [Mutation and Post Request](#mutation-and-post-request)
- [SSR with Next.js](#ssr-with-nextjs)
- [Suspense Mode](#suspense-mode)
- [Error Retries](#error-retries)
- [Prefetching Data](#prefetching-data)

@@ -180,3 +181,3 @@ ### Global Configuration

`fetcher` is a function **accepts the `key`** of SWR, and returns a value or a Promise.
`fetcher` is a function that **accepts the `key`** of SWR, and returns a value or a Promise.
You can use any library to handle data fetching, for example:

@@ -220,3 +221,3 @@

Note that `fetcher` can be skipped from the parameters if it's provided gloablly.
Note that `fetcher` can be omitted from the parameters if it's provided globally.

@@ -317,3 +318,3 @@ ### Conditional Fetching

### Local Mutation
### Mutation and Post Request

@@ -365,3 +366,3 @@ In many cases, applying local mutations to data is a good way to make changes

```js
App.getInitialProps = async getInitialProps () {
App.getInitialProps = async () => {
const data = await fetcher('/api/data')

@@ -428,2 +429,25 @@ return { data }

### Prefetching Data
There’re many ways to prefetch the data for SWR. For top level requests, [`rel="preload"`](https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content) is highly recommended:
```html
<link rel="preload" href="/api/data" as="fetch" crossorigin="anonymous">
```
This will prefetch the data before the JavaScript starts downloading. And your incoming fetch requests will reuse the result (including SWR, of course).
Another choice is to prefetch the data conditionally. You can have a function to refetch and set the cache:
```js
function prefetch () {
mutate('/api/data', fetch('/api/data').then(res => res.json()))
// the second parameter is a Promise
// SWR will use the result when it resolves
}
```
And use it when you need to preload the **resources** (for example when [hovering](https://github.com/GoogleChromeLabs/quicklink) [a](https://github.com/guess-js/guess) [link](https://instant.page)).
Together with techniques like [page prefetching](https://nextjs.org/docs#prefetching-pages) in Next.js, you will be able to load both next page and data instantly.
<br/>

@@ -430,0 +454,0 @@

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