UNPKG

react-query

Version:

Hooks for managing, caching and syncing asynchronous and remote data in React

3 lines (2 loc) 16.2 kB
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],r):r((e=e||self).ReactQuery={},e.React)}(this,(function(e,r){"use strict";function t(){return(t=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}function n(e,r){if(null==e)return{};var t,n,u={},i=Object.keys(e);for(n=0;n<i.length;n++)t=i[n],r.indexOf(t)>=0||(u[t]=e[t]);return u}r=r&&r.hasOwnProperty("default")?r.default:r;var u=0,i=function(){return u++},o={},c="undefined"==typeof window,a=function(){},s=console||{error:a,warn:a,log:a};function f(e){var t=r.useRef();return t.current=e,r.useCallback((function(){return t.current}),[])}function l(e,r){return"function"==typeof e?e(r):e}function d(e,r){return v(r)?Object.assign.apply(Object,[{}].concat(Object.keys(r).sort().map((function(e){var t;return(t={})[e]=r[e],t})))):r}function h(e){return JSON.stringify(e,d)}function v(e){return e&&"object"==typeof e&&!Array.isArray(e)}function y(){return"undefined"==typeof document||void 0===document.visibilityState||"visible"===document.visibilityState||"prerender"===document.visibilityState}function p(e){if(v(e[0])){if(e[0].hasOwnProperty("queryKey")&&e[0].hasOwnProperty("queryFn")){var r=e[0],t=r.queryKey,n=r.variables,u=void 0===n?[]:n,i=r.queryFn,o=r.config;return[t,u,i,void 0===o?{}:o]}throw new Error("queryKey and queryFn keys are required.")}if("function"==typeof e[2]){var c=e[0],a=e[1],s=void 0===a?[]:a,f=e[2],l=e[3];return[c,s,f,void 0===l?{}:l]}var d=e[0],h=e[1],y=e[2];return[d,[],h,void 0===y?{}:y]}function g(e){var t=r.useRef(!1);return r[c?"useEffect":"useLayoutEffect"]((function(){return t.current=!0,function(){return t.current=!1}}),[]),r.useCallback((function(){return t.current?e.apply(void 0,arguments):void 0}),[e])}var w=r.createContext(),m={current:{retry:3,retryDelay:function(e){return Math.min(1e3*Math.pow(2,e),3e4)},staleTime:0,cacheTime:3e5,refetchAllOnWindowFocus:!0,refetchInterval:!1,suspense:!1,queryKeySerializerFn:function e(r){if(!r)return[];if("function"==typeof r)try{return e(r())}catch(e){return[]}"string"==typeof r&&(r=[r]);var t=h(r);return r=JSON.parse(t),[t,r]},queryFnParamsFilter:function(e){return e},throwOnError:!1,useErrorBoundary:void 0,onSuccess:a,onError:a,onSettled:a,refetchOnMount:!0}};function q(){return r.useContext(w)||m.current}function b(e,r,t){return t?r?r(e):e:(e&&e.then||(e=Promise.resolve(e)),r?e.then(r):e)}function S(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}function F(e){return function(){for(var r=[],t=0;t<arguments.length;t++)r[t]=arguments[t];try{return Promise.resolve(e.apply(this,r))}catch(e){return Promise.reject(e)}}}function E(e,r){var t=e();return t&&t.then?t.then(r):r(t)}var O=function(){var e=[],r={queries:{},isFetching:0},u=function(){r.isFetching=Object.values(O.queries).reduce((function(e,r){return r.state.isFetching?e+1:e}),0),e.forEach((function(e){return e(r)}))};r.subscribe=function(r){return e.push(r),function(){e.splice(e.indexOf(r),1)}},r.clear=function(){r.queries={},u()};var i=function(e,t){var n=(void 0===t?{}:t).exact;if("function"!=typeof e){var u=m.current.queryKeySerializerFn(e),i=u[0],o=u[1];e=function(e){return n?e.queryHash===i:function e(r,t){return typeof r==typeof t&&("object"==typeof r?!Object.keys(t).some((function(n){return!e(r[n],t[n])})):r===t)}(e.queryKey,o)}}return Object.values(r.queries).filter(e)};return r.getQueries=i,r.getQuery=function(e){return i(e,{exact:!0})[0]},r.getQueryData=function(e){var t;return null==(t=r.getQuery(e))?void 0:t.state.data},r.removeQueries=function(e,t){var n=(void 0===t?{}:t).exact,o=i(e,{exact:n});o.forEach((function(e){clearTimeout(e.staleTimeout),delete r.queries[e.queryHash]})),o.length&&u()},r.refetchQueries=F((function(e,t){var n=void 0===t?{}:t,u=n.exact,o=n.throwOnError,c=n.force,a=!0===e?Object.values(r.queries):i(e,{exact:u});return S((function(){return b(Promise.all(a.map((function(e){return e.fetch({force:c})}))))}),(function(e){if(o)throw e}))})),r._buildQuery=function(e,n,i,s){var f=s.queryKeySerializerFn(e),d=f[0],h=f[1],v=r.queries[d];return v?(Object.assign(v,{queryVariables:n,queryFn:i}),Object.assign(v.config,s)):((v=function(e){var n=e.config.queryReducer||D,i=void 0===e.queryHash,c="function"==typeof e.config.initialData?e.config.initialData():e.config.initialData,s=void 0!==c,f=!!i||!s,d=e.config.manual,h=t({},e,{instances:[],state:n(void 0,{type:P,initialStatus:i||d||s?"success":"loading",initialData:c,hasInitialData:s,isStale:f,manual:d})}),v=function(e){h.state=n(h.state,e),h.instances.forEach((function(e){return e.onStateUpdate(h.state)})),u()};h.scheduleStaleTimeout=function(){h.config.staleTime!==1/0&&(h.staleTimeout=setTimeout((function(){v({type:I})}),h.config.staleTime))},h.scheduleGarbageCollection=function(){h.cacheTimeout=setTimeout((function(){r.removeQueries((function(e){return e.queryHash===h.queryHash}))}),void 0===h.state.data&&"error"!==h.state.status?0:h.config.cacheTime)},h.heal=function(){clearTimeout(h.cacheTimeout),h.cancelled=null},h.subscribe=function(e){var r=h.instances.find((function(r){return r.id===e.id}));return r?Object.assign(r,e):(r=t({onStateUpdate:a},e),h.instances.push(e)),h.heal(),function(){h.instances=h.instances.filter((function(r){return r.id!==e.id})),h.instances.length||(h.cancelled=o,h.cancelQueries&&h.cancelQueries(),h.scheduleGarbageCollection())}};var p=F((function(e){for(var r=arguments.length,t=new Array(r>1?r-1:0),n=1;n<r;n++)t[n-1]=arguments[n];return S((function(){var r=e.apply(void 0,h.config.queryFnParamsFilter(t));return h.cancelQueries=function(){return null==r.cancel?void 0:r.cancel()},b(r,(function(e){if(delete h.cancelQueries,h.cancelled)throw h.cancelled;return e}))}),(function(r){var n=!1;if(delete h.cancelQueries,h.cancelled)throw h.cancelled;return v({type:C}),E((function(){if(!0===h.config.retry||h.state.failureCount<=h.config.retry){if(!y())return h.shouldContinueRetryOnFocus=!0,n=!0,new Promise(a);delete h.shouldContinueRetryOnFocus;var r=l(h.config.retryDelay,h.state.failureCount);return n=!0,b(new Promise((function(n,u){setTimeout(F((function(){return h.cancelled?u(h.cancelled):S((function(){return b(p.apply(void 0,[e].concat(t)),(function(e){if(h.cancelled)return u(h.cancelled);n(e)}))}),(function(e){if(h.cancelled)return u(h.cancelled);u(e)}))})),r)})))}}),(function(e){if(n)return e;throw r}))}))}));return h.fetch=F((function(e){var r=void 0===e?{}:e,t=r.force,n=r.__queryFn,u=void 0===n?h.queryFn:n;if(h.queryHash&&(h.state.isStale||t))return h.promise||(h.promise=F((function(){return h.cancelled=null,S((function(){return v({type:M}),b(p.apply(void 0,[u].concat(h.queryKey,h.queryVariables)),(function(e){return h.setData(e),h.instances.forEach((function(e){return e.onSuccess&&e.onSuccess(h.state.data)})),h.instances.forEach((function(e){return e.onSettled&&e.onSettled(h.state.data,null)})),delete h.promise,e}))}),(function(e){v({type:j,cancelled:e===h.cancelled,error:e}),delete h.promise,e!==h.cancelled&&(h.instances.forEach((function(r){return r.onError&&r.onError(e)})),h.instances.forEach((function(r){return r.onSettled&&r.onSettled(void 0,e)})))}))}))()),h.promise})),h.setData=function(e){v({type:Q,updater:e}),clearTimeout(h.staleTimeout),h.scheduleStaleTimeout()},h}({queryKey:h,queryHash:d,queryVariables:n,queryFn:i,config:s})).state.data&&(v.scheduleStaleTimeout(),v.heal(),v.scheduleGarbageCollection()),v.queryHash&&(c||(r.queries[d]=v,u()))),v},r.prefetchQuery=F((function(){for(var e=!1,u=arguments.length,i=new Array(u),o=0;o<u;o++)i[o]=arguments[o];var c=p(i),a=c[0],s=c[1],f=c[2],l=c[3],d=l.force,h=n(l,["force"]);h=t({},m.current,{},h);var v=r._buildQuery(a,s,f,h);return E((function(){if(v.state.isStale||d)return S((function(){return b(v.fetch(),(function(r){return v.wasPrefetched=!0,e=!0,r}))}),(function(e){if(h.throwOnError)throw e}))}),(function(r){return e?r:v.state.data}))})),r.setQueryData=function(e,u,o){void 0===o&&(o={});var c=o,s=c.exact,f=n(c,["exact"]),l=i(e,{exact:s});l.length||"function"==typeof e||(l=[r._buildQuery(e,void 0,(function(){return new Promise(a)}),t({},m.current,{},f))]),l.forEach((function(e){return e.setData(u)}))},r}(),P={},C={},I={},M={},Q={},j={};function D(e,r){switch(r.type){case P:return{status:r.initialStatus,error:null,isFetching:!r.hasInitialData&&!r.manual,canFetchMore:!1,failureCount:0,isStale:r.isStale,data:r.initialData,updatedAt:r.hasInitialData?Date.now():0};case C:return t({},e,{failureCount:e.failureCount+1});case I:return t({},e,{isStale:!0});case M:return t({},e,{status:"error"===e.status?"loading":e.status,isFetching:!0,failureCount:0});case Q:return t({},e,{status:"success",data:l(r.updater,e.data),error:null,isStale:!1,isFetching:!1,canFetchMore:r.canFetchMore,updatedAt:Date.now(),failureCount:0});case j:return t({},e,{isFetching:!1},!r.cancelled&&{status:"error",error:r.error,isStale:!0});default:throw new Error}}var T,x=function(){var e=m.current.refetchAllOnWindowFocus;y()&&(void 0===navigator.onLine||navigator.onLine)&&O.refetchQueries((function(r){return!!r.instances.length&&(r.shouldContinueRetryOnFocus?(delete r.promise,!0):void 0===r.config.refetchOnWindowFocus?e:r.config.refetchOnWindowFocus)})).catch(s.error)};function R(e){T&&T(),T=e(x)}function k(e,r,t){return t?r?r(e):e:(e&&e.then||(e=Promise.resolve(e)),r?e.then(r):e)}R((function(e){var r;if(!c&&(null==(r=window)?void 0:r.addEventListener))return window.addEventListener("visibilitychange",e,!1),window.addEventListener("focus",e,!1),function(){window.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e)}}));var A=function(){return{status:"idle",data:void 0,error:null}};var H={};var K={},_={},L={};function V(e,r){if(r.type===H)return{status:"idle",data:void 0,error:null};if(r.type===K)return{status:"loading"};if("loading"===e.status&&r.type===_)return{status:"success",data:r.data};if("loading"===e.status&&r.type===L)return{status:"error",error:r.error};throw new Error}function B(e,u,o,c){void 0===c&&(c={});var a,l=(null===(a=r.useRef(null)).current&&(a.current=i()),a.current);c=t({},q(),{},c);var d=r.useRef(),h=O._buildQuery(e,u,o,c);d.current&&void 0===d.current.queryHash&&void 0===h.queryHash||(d.current=h);var v,p=d.current,w=g(r.useState()[1]),m=f(c),b=r.useCallback((v=function(e){void 0===e&&(e={});var r=e,t=r.throwOnError,u=n(r,["throwOnError"]);return function(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}((function(){return e=p.fetch(u),t?r?r(e):e:(e&&e.then||(e=Promise.resolve(e)),r?e.then(r):e);var e,r,t}),(function(e){if(t)throw e}))},function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];try{return Promise.resolve(v.apply(this,e))}catch(e){return Promise.reject(e)}}),[p]);return r.useEffect((function(){var e=p.subscribe({id:l,onStateUpdate:function(){return w({})},onSuccess:function(e){return m().onSuccess(e)},onError:function(e){return m().onError(e)},onSettled:function(e,r){return m().onSettled(e,r)}});return m().manual||p.wasPrefetched||p.wasSuspensed||!p.state.isStale||!m().refetchOnMount&&1!==p.instances.length||b().catch(s.error),p.wasPrefetched=!1,p.wasSuspensed=!1,e}),[m,l,p,b,w]),r.useEffect((function(){if(c.refetchInterval&&(!p.refetchInterval||c.refetchInterval<p.refetchInterval))return clearInterval(p.refetchInterval),p.refetchInterval=setInterval((function(){(y()||c.refetchIntervalInBackground)&&b().catch(s.error)}),c.refetchInterval),function(){clearInterval(p.refetchInterval),delete p.refetchInterval}}),[c.refetchInterval,c.refetchIntervalInBackground,p.refetchInterval,b]),t({},p.state,{config:c,query:p,refetch:b})}function W(e,r,t){return t?r?r(e):e:(e&&e.then||(e=Promise.resolve(e)),r?e.then(r):e)}function z(e){return function(){for(var r=[],t=0;t<arguments.length;t++)r[t]=arguments[t];try{return Promise.resolve(e.apply(this,r))}catch(e){return Promise.reject(e)}}}function G(e,r){if(e)throw r;return r}function U(e,r){try{var t=e()}catch(e){return r(!0,e)}return t&&t.then?t.then(r.bind(null,!1),r.bind(null,!0)):r(!1,t)}e.ReactQueryConfigProvider=function(e){var n=e.config,u=e.children,i=r.useContext(w),o=r.useMemo((function(){var e=t({},i||m.current,{},n);return void 0===e.useErrorBoundary&&(e.useErrorBoundary=e.suspense),e}),[n,i]);return i||(m.current=o),r.createElement(w.Provider,{value:o},u)},e.queryCache=O,e.setConsole=function(e){s=e},e.setFocusHandler=R,e.stableStringify=h,e.statusError="error",e.statusIdle="idle",e.statusLoading="loading",e.statusSuccess="success",e.useInfiniteQuery=function(){for(var e=r.useRef(),n=arguments.length,u=new Array(n),i=0;i<n;i++)u[i]=arguments[i];var o=p(u),c=o[0],a=o[1],s=o[2],l=o[3],d=void 0===l?{}:l,h=d.getFetchMore,v=f(h),y=s,g=B(c,a,s=z((function(){return W(Promise.all(e.current.query.pageVariables.map((function(e){return y.apply(void 0,e)}))),(function(r){return e.current.query.canFetchMore=v()(r[r.length-1],r),r}))})),d);e.current=g;var w=g.refetch,m=g.data,q=void 0===m?[]:m,b=g.query.canFetchMore;g.query.pageVariables||(g.query.pageVariables=[[].concat(g.query.queryKey,g.query.queryVariables)]);var S=r.useCallback((function(r){return void 0===r&&(r=e.current.query.canFetchMore),w({force:!0,__queryFn:z((function(){for(var t=arguments.length,n=new Array(t),u=0;u<t;u++)n[u]=arguments[u];return U((function(){e.current.query.isFetchingMore=!0;var t=[].concat(n,[r]);e.current.query.pageVariables.push(t);var u=e.current.data;return W(y.apply(void 0,t),(function(r){var t=[].concat(u,[r]);return e.current.query.canFetchMore=v()(t[t.length-1],t),t}))}),(function(r,t){return e.current.query.isFetchingMore=!1,G(r,t)}))}))})}),[v,y,w]),F=r.useMemo((function(){return!!g.query.isFetchingMore}),[g.query.isFetchingMore]);if(g.config.suspense){if("error"===g.status)throw g.error;if("loading"===g.status)throw g.wasSuspensed=!0,g.refetch()}return t({},g,{data:q,canFetchMore:b,fetchMore:S,isFetchingMore:F})},e.useIsFetching=function(){var e=r.useState({}),t=e[0],n=e[1];return r.useEffect((function(){return O.subscribe((function(){return n({})}))}),[]),r.useMemo((function(){return t&&O.isFetching}),[t])},e.useMutation=function(e,n){void 0===n&&(n={});var u,o=r.useReducer(V,null,A),c=o[0],a=g(o[1]),l=f(e),d=f(t({},q(),{},n)),h=r.useRef(),v=r.useCallback((u=function(e,r){void 0===r&&(r={});var n=t({},d(),{},r),u=i();return h.current=u,a({type:K}),function(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}((function(){return k(l()(e),(function(e){return k(n.onSuccess(e),(function(){return k(n.onSettled(e,null),(function(){return h.current===u&&a({type:_,data:e}),e}))}))}))}),(function(e){return s.error(e),k(n.onError(e),(function(){return k(n.onSettled(void 0,e),(function(){if(h.current===u&&a({type:L,error:e}),n.throwOnError)throw e}))}))}))},function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];try{return Promise.resolve(u.apply(this,e))}catch(e){return Promise.reject(e)}}),[a,d,l]),y=r.useCallback((function(){return a({type:H})}),[a]);return r.useEffect((function(){if(d().useErrorBoundary&&c.error)throw c.error}),[d,c.error]),[v,t({},c,{reset:y})]},e.usePaginatedQuery=function(){for(var e=arguments.length,n=new Array(e),u=0;u<e;u++)n[u]=arguments[u];var i=p(n),o=i[0],c=i[1],a=i[2],s=i[3],f=void 0===s?{}:s,l=r.useRef();void 0!==l.current&&delete f.initialData;var d=B(o,c,a,f),h=d.data,v=d.status;r.useEffect((function(){"success"===v&&void 0!==h&&(l.current=h)}),[h,v]);var y=h;if(void 0===y&&(y=l.current),void 0!==y&&(v="success"),d.config.suspense){if("error"===d.status)throw d.error;if("loading"===d.status)throw d.wasSuspensed=!0,d.refetch()}return t({},d,{resolvedData:y,latestData:h,status:v})},e.useQuery=function(){for(var e=arguments.length,r=new Array(e),t=0;t<e;t++)r[t]=arguments[t];var n=B.apply(void 0,p(r));if(n.config.suspense){if("error"===n.status)throw n.error;if("loading"===n.status)throw n.wasSuspensed=!0,n.refetch()}return n},Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=react-query.production.min.js.map