@ahooksjs/use-request
Advanced tools
Comparing version 2.0.1 to 2.0.2
@@ -1,1 +0,1 @@ | ||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("React")):"function"==typeof define&&define.amd?define(["React"],e):"object"==typeof exports?exports.ahooksUseRequest=e(require("React")):t.ahooksUseRequest=e(t.React)}(this,(function(t){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=4)}([function(e,n){e.exports=t},function(t,e){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){(function(e){var n=/^\s+|\s+$/g,r=/^[-+]0x[0-9a-f]+$/i,i=/^0b[01]+$/i,o=/^0o[0-7]+$/i,u=parseInt,a="object"==typeof e&&e&&e.Object===Object&&e,c="object"==typeof self&&self&&self.Object===Object&&self,s=a||c||Function("return this")(),f=Object.prototype.toString,l=Math.max,d=Math.min,h=function(){return s.Date.now()};function v(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function p(t){if("number"==typeof t)return t;if(function(t){return"symbol"==typeof t||function(t){return!!t&&"object"==typeof t}(t)&&"[object Symbol]"==f.call(t)}(t))return NaN;if(v(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=v(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(n,"");var a=i.test(t);return a||o.test(t)?u(t.slice(2),a?2:8):r.test(t)?NaN:+t}t.exports=function(t,e,n){var r,i,o,u,a,c,s=0,f=!1,g=!1,b=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function y(e){var n=r,o=i;return r=i=void 0,s=e,u=t.apply(o,n)}function m(t){return s=t,a=setTimeout(j,e),f?y(t):u}function O(t){var n=t-c;return void 0===c||n>=e||n<0||g&&t-s>=o}function j(){var t=h();if(O(t))return w(t);a=setTimeout(j,function(t){var n=e-(t-c);return g?d(n,o-(t-s)):n}(t))}function w(t){return a=void 0,b&&r?y(t):(r=i=void 0,u)}function T(){var t=h(),n=O(t);if(r=arguments,i=this,c=t,n){if(void 0===a)return m(c);if(g)return a=setTimeout(j,e),y(c)}return void 0===a&&(a=setTimeout(j,e)),u}return e=p(e)||0,v(n)&&(f=!!n.leading,o=(g="maxWait"in n)?l(p(n.maxWait)||0,e):o,b="trailing"in n?!!n.trailing:b),T.cancel=function(){void 0!==a&&clearTimeout(a),s=0,r=c=i=a=void 0},T.flush=function(){return void 0===a?u:w(h())},T}}).call(this,n(1))},function(t,e,n){(function(e){var n=/^\s+|\s+$/g,r=/^[-+]0x[0-9a-f]+$/i,i=/^0b[01]+$/i,o=/^0o[0-7]+$/i,u=parseInt,a="object"==typeof e&&e&&e.Object===Object&&e,c="object"==typeof self&&self&&self.Object===Object&&self,s=a||c||Function("return this")(),f=Object.prototype.toString,l=Math.max,d=Math.min,h=function(){return s.Date.now()};function v(t,e,n){var r,i,o,u,a,c,s=0,f=!1,v=!1,b=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function y(e){var n=r,o=i;return r=i=void 0,s=e,u=t.apply(o,n)}function m(t){return s=t,a=setTimeout(j,e),f?y(t):u}function O(t){var n=t-c;return void 0===c||n>=e||n<0||v&&t-s>=o}function j(){var t=h();if(O(t))return w(t);a=setTimeout(j,function(t){var n=e-(t-c);return v?d(n,o-(t-s)):n}(t))}function w(t){return a=void 0,b&&r?y(t):(r=i=void 0,u)}function T(){var t=h(),n=O(t);if(r=arguments,i=this,c=t,n){if(void 0===a)return m(c);if(v)return a=setTimeout(j,e),y(c)}return void 0===a&&(a=setTimeout(j,e)),u}return e=g(e)||0,p(n)&&(f=!!n.leading,o=(v="maxWait"in n)?l(g(n.maxWait)||0,e):o,b="trailing"in n?!!n.trailing:b),T.cancel=function(){void 0!==a&&clearTimeout(a),s=0,r=c=i=a=void 0},T.flush=function(){return void 0===a?u:w(h())},T}function p(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function g(t){if("number"==typeof t)return t;if(function(t){return"symbol"==typeof t||function(t){return!!t&&"object"==typeof t}(t)&&"[object Symbol]"==f.call(t)}(t))return NaN;if(p(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=p(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(n,"");var a=i.test(t);return a||o.test(t)?u(t.slice(2),a?2:8):r.test(t)?NaN:+t}t.exports=function(t,e,n){var r=!0,i=!0;if("function"!=typeof t)throw new TypeError("Expected a function");return p(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),v(t,e,{leading:r,maxWait:e,trailing:i})}}).call(this,n(1))},function(t,e,n){"use strict";n.r(e),n.d(e,"useAsync",(function(){return T})),n.d(e,"usePaginated",(function(){return S})),n.d(e,"useLoadMore",(function(){return E})),n.d(e,"UseRequestProvider",(function(){return P})),n.d(e,"UseAPIProvider",(function(){return D}));function r(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]])}return n}var i=n(0),o=n.n(i),u=n(2),a=n.n(u),c=n(3),s=n.n(c);function f(){return"undefined"==typeof document||void 0===document.visibilityState||"hidden"!==document.visibilityState}var l={};var d=function(t){var e=Object(i.useRef)((function(){throw new Error("Cannot call an event handler while rendering.")}));e.current=t;var n=Object(i.useCallback)((function(){var t=e.current;if(t)return t.apply(void 0,arguments)}),[e]);if("function"==typeof t)return n},h=function(t,e){var n=Object(i.useRef)(!1);Object(i.useEffect)((function(){if(n.current)return t();n.current=!0}),e)},v=[];var p=!1;if("undefined"!=typeof window&&window.addEventListener&&!p){var g=function(){if(f()&&(void 0===navigator.onLine||navigator.onLine))for(var t=0;t<v.length;t++){(0,v[t])()}};window.addEventListener("visibilitychange",g,!1),window.addEventListener("focus",g,!1),p=!0}var b=function(t){return v.push(t),function(){var e=v.indexOf(t);v.splice(e,1)}},y=[];var m=!1;if("undefined"!=typeof window&&window.addEventListener&&!m){window.addEventListener("visibilitychange",(function(){if(f())for(var t=0;t<y.length;t++){(0,y[t])()}}),!1),m=!0}var O=function(t){return y.push(t),function(){var e=y.indexOf(t);y.splice(e,1)}},j="AHOOKS_USE_REQUEST_DEFAULT_KEY",w=function(){function t(t,e,n,r){var i,o,u;this.count=0,this.unmountedFlag=!1,this.pollingWhenVisibleFlag=!1,this.pollingTimer=void 0,this.loadingDelayTimer=void 0,this.unsubscribe=[],this.that=this,this.state={loading:!1,params:[],data:void 0,error:void 0,run:this.run.bind(this.that),mutate:this.mutate.bind(this.that),refresh:this.refresh.bind(this.that),cancel:this.cancel.bind(this.that),unmount:this.unmount.bind(this.that)},this.service=t,this.config=e,this.subscribe=n,r&&(this.state=Object.assign(Object.assign({},this.state),r)),this.debounceRun=this.config.debounceInterval?a()(this._run,this.config.debounceInterval):void 0,this.throttleRun=this.config.throttleInterval?s()(this._run,this.config.throttleInterval):void 0,this.limitRefresh=(i=this.refresh.bind(this),o=this.config.focusTimespan,u=!1,function(){u||(u=!0,i.apply(void 0,arguments),setTimeout((function(){u=!1}),o))}),this.config.pollingInterval&&this.unsubscribe.push(O(this.rePolling.bind(this))),this.config.refreshOnWindowFocus&&this.unsubscribe.push(b(this.limitRefresh.bind(this)))}var e=t.prototype;return e.setState=function(t){void 0===t&&(t={}),this.state=Object.assign(Object.assign({},this.state),t),this.subscribe(this.state)},e._run=function(){for(var t=this,e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];this.pollingTimer&&clearTimeout(this.pollingTimer),this.loadingDelayTimer&&clearTimeout(this.loadingDelayTimer),this.count+=1;var i=this.count;return this.setState({loading:!this.config.loadingDelay,params:n}),this.config.loadingDelay&&(this.loadingDelayTimer=setTimeout((function(){t.setState({loading:!0})}),this.config.loadingDelay)),this.service.apply(this,n).then((function(e){if(!t.unmountedFlag&&i===t.count){t.loadingDelayTimer&&clearTimeout(t.loadingDelayTimer);var r=t.config.formatResult?t.config.formatResult(e):e;return t.setState({data:r,error:void 0,loading:!1}),t.config.onSuccess&&t.config.onSuccess(r,n),r}})).catch((function(e){if(!t.unmountedFlag&&i===t.count){if(t.loadingDelayTimer&&clearTimeout(t.loadingDelayTimer),t.setState({data:void 0,error:e,loading:!1}),t.config.onError&&t.config.onError(e,n),t.config.throwOnError)throw e;console.error(e)}})).finally((function(){if(!t.unmountedFlag&&i===t.count&&t.config.pollingInterval){if(!f()&&!t.config.pollingWhenHidden)return void(t.pollingWhenVisibleFlag=!0);t.pollingTimer=setTimeout((function(){t._run.apply(t,n)}),t.config.pollingInterval)}}))},e.run=function(){return this.debounceRun?(this.debounceRun.apply(this,arguments),Promise.resolve(null)):this.throttleRun?(this.throttleRun.apply(this,arguments),Promise.resolve(null)):this._run.apply(this,arguments)},e.cancel=function(){this.debounceRun&&this.debounceRun.cancel(),this.throttleRun&&this.throttleRun.cancel(),this.loadingDelayTimer&&clearTimeout(this.loadingDelayTimer),this.pollingTimer&&clearTimeout(this.pollingTimer),this.pollingWhenVisibleFlag=!1,this.count+=1,this.setState({loading:!1})},e.refresh=function(){return this.run.apply(this,this.state.params)},e.rePolling=function(){this.pollingWhenVisibleFlag&&(this.pollingWhenVisibleFlag=!1,this.refresh())},e.mutate=function(t){"function"==typeof t?this.setState({data:t(this.state.data)||{}}):this.setState({data:t})},e.unmount=function(){this.unmountedFlag=!0,this.cancel(),this.unsubscribe.forEach((function(t){t()}))},t}();var T=function(t,e){var n,r=e||{},o=r.refreshDeps,u=void 0===o?[]:o,a=r.manual,c=void 0!==a&&a,s=r.onSuccess,f=void 0===s?function(){}:s,v=r.onError,p=void 0===v?function(){}:v,g=r.defaultLoading,b=void 0!==g&&g,y=r.loadingDelay,m=r.pollingInterval,O=void 0===m?0:m,T=r.pollingWhenHidden,E=void 0===T||T,S=r.defaultParams,R=void 0===S?[]:S,x=r.refreshOnWindowFocus,P=void 0!==x&&x,D=r.focusTimespan,M=void 0===D?5e3:D,C=r.fetchKey,F=r.cacheKey,k=r.debounceInterval,I=r.throttleInterval,W=r.initialData,_=r.ready,K=void 0===_||_,L=r.throwOnError,N=void 0!==L&&L,z=Object(i.useRef)(j),q=d(t),U=d(f),$=d(p),A=d(C);"formatResult"in r&&(n=r.formatResult);var H={formatResult:d(n),onSuccess:U,onError:$,loadingDelay:y,pollingInterval:O,pollingWhenHidden:E,refreshOnWindowFocus:P,focusTimespan:M,debounceInterval:k,throttleInterval:I,throwOnError:N},V=d((function(t,e){B((function(n){return n[t]=e,Object.assign({},n)}))})),Y=Object(i.useState)((function(){if(F){var t=null===(n=l[F])||void 0===n?void 0:n.data;if(t){z.current=t.newstFetchKey;var e={};return Object.keys(t.fetches).forEach((function(n){var r=t.fetches[n],i=new w(q,H,V.bind(null,n),{loading:r.loading,params:r.params,data:r.data,error:r.error});e[n]=i.state})),e}}var n;return[]})),Q=Y[0],B=Y[1],G=Object(i.useRef)(Q);G.current=Q;var J=Object(i.useRef)(),X=Object(i.useCallback)((function(){for(var t,e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];if(K){if(A){var i=A.apply(void 0,n);z.current=void 0===i?j:i}var o=z.current,u=G.current[o];if(!u){var a=new w(q,H,V.bind(null,o),{data:W});u=a.state,B((function(t){return t[o]=u,Object.assign({},t)}))}return(t=u).run.apply(t,n)}J.current=n}),[C,V,K]),Z=Object(i.useRef)(X);Z.current=X,Object(i.useEffect)((function(){F&&function(t,e){l[t]&&clearTimeout(l[t].timer);var n=setTimeout((function(){delete l[t]}),3e5);l[t]={data:e,timer:n}}(F,{fetches:Q,newstFetchKey:z.current})}),[F,Q]);var tt=Object(i.useRef)(!1);h((function(){K&&(!tt.current&&J.current&&Z.current.apply(Z,J.current),tt.current=!0)}),[K]),Object(i.useEffect)((function(){c||(Object.keys(Q).length>0?Object.values(Q).forEach((function(t){t.refresh()})):Z.current.apply(Z,R))}),[]);var et=Object(i.useCallback)((function(){Object.values(G.current).forEach((function(t){t.unmount()})),z.current=j,B({}),G.current={}}),[B]);h((function(){c||Object.values(G.current).forEach((function(t){t.refresh()}))}),[].concat(u)),Object(i.useEffect)((function(){return function(){Object.values(G.current).forEach((function(t){t.unmount()}))}}),[]);var nt=Object(i.useCallback)((function(t){return function(){throw new Error("Cannot call "+t+" when service not executed once.")}}),[]);return Object.assign(Object.assign({loading:K&&!c||b,data:W,error:void 0,params:[],cancel:nt("cancel"),refresh:nt("refresh"),mutate:nt("mutate")},Q[z.current]||{}),{run:X,fetches:Q,reset:et})};var E=function(t,e){var n=e.refreshDeps,o=void 0===n?[]:n,u=e.ref,a=e.isNoMore,c=e.threshold,s=void 0===c?100:c,f=(e.fetchKey,r(e,["refreshDeps","ref","isNoMore","threshold","fetchKey"])),l=Object(i.useState)(!1),d=l[0],v=l[1];Object(i.useEffect)((function(){e.fetchKey&&console.warn("useRequest loadMore mode don't need fetchKey!")}),[]);var p=T(t,Object.assign(Object.assign({},f),{fetchKey:function(t){var e;return(null===(e=null==t?void 0:t.list)||void 0===e?void 0:e.length)||0},onSuccess:function(){v(!1),e.onSuccess&&e.onSuccess.apply(e,arguments)}})),g=p.data,b=p.run,y=p.params,m=p.reset,O=p.loading,j=p.fetches,w=Object(i.useCallback)((function(){m();var t=y.slice(1);b.apply(void 0,[void 0].concat(t))}),[b,m,y]),E=Object(i.useRef)(w);E.current=w,h((function(){e.manual||E.current()}),[].concat(o));var S=Object(i.useMemo)((function(){var t=[],e=g;return Object.values(j).forEach((function(n){var r,i;(null===(r=n.data)||void 0===r?void 0:r.list)&&(t=t.concat(null===(i=n.data)||void 0===i?void 0:i.list)),n.loading||(e=n.data)})),Object.assign(Object.assign({},e),{list:t})}),[j,g]),R=!!a&&(!O&&!d&&a(S)),x=Object(i.useCallback)((function(){if(!R){v(!0);var t=y.slice(1);b.apply(void 0,[S].concat(t))}}),[R,b,S,y]),P=Object(i.useCallback)((function(){!O&&!d&&u&&u.current&&u.current.scrollHeight-u.current.scrollTop<=u.current.clientHeight+s&&x()}),[O,u,x]);return Object(i.useEffect)((function(){return u&&u.current?(u.current.addEventListener("scroll",P),function(){u&&u.current&&u.current.removeEventListener("scroll",P)}):function(){}}),[P]),Object.assign(Object.assign({},p),{data:S,reload:w,loading:O&&0===S.list.length,loadMore:x,loadingMore:d,noMore:R})};var S=function(t,e){e.paginated;var n=e.defaultPageSize,o=void 0===n?10:n,u=e.refreshDeps,a=void 0===u?[]:u,c=e.fetchKey,s=r(e,["paginated","defaultPageSize","refreshDeps","fetchKey"]);Object(i.useEffect)((function(){c&&console.error("useRequest pagination's fetchKey will not work!")}),[]);var f=T(t,Object.assign({defaultParams:[{current:1,pageSize:o}]},s)),l=f.data,d=f.params,v=f.run,p=f.loading,g=r(f,["data","params","run","loading"]),b=d&&d[0]?d[0]:{},y=b.current,m=void 0===y?1:y,O=b.pageSize,j=void 0===O?o:O,w=b.sorter,E=void 0===w?{}:w,S=b.filters,R=void 0===S?{}:S,x=Object(i.useCallback)((function(t){var e=d[0],n=d.slice(1);v.apply(void 0,[Object.assign(Object.assign({},e),t)].concat(n))}),[v,d]),P=(null==l?void 0:l.total)||0,D=Object(i.useMemo)((function(){return Math.ceil(P/j)}),[j,P]),M=Object(i.useCallback)((function(t,e){var n=t<=0?1:t,r=e<=0?1:e,i=Math.ceil(P/r);n>i&&(n=i),x({current:t,pageSize:e})}),[P,x]),C=Object(i.useCallback)((function(t){M(t,j)}),[M,j]),F=Object(i.useCallback)((function(t){M(m,t)}),[M,m]),k=Object(i.useRef)(C);k.current=C,h((function(){e.manual||k.current(1)}),[].concat(a));var I=Object(i.useCallback)((function(t,e,n){x({current:t.current,pageSize:t.pageSize||o,filters:e,sorter:n})}),[R,E,x]);return Object.assign({loading:p,data:l,params:d,run:v,pagination:{current:m,pageSize:j,total:P,totalPage:D,onChange:M,changeCurrent:C,changePageSize:F},tableProps:{dataSource:(null==l?void 0:l.list)||[],loading:p,onChange:I,pagination:{current:m,pageSize:j,total:P}},sorter:E,filters:R},g)},R=o.a.createContext({});R.displayName="UseRequestConfigContext";var x=R;var P=x.Provider,D=P;e.default=function(t,e){void 0===e&&(e={});var n=Object(i.useContext)(x),o=Object.assign(Object.assign({},n),e),u=o.paginated,a=o.loadMore,c=o.requestMethod,s=Object(i.useRef)(u),f=Object(i.useRef)(a);if(s.current!==u)throw Error("You should not modify the paginated of options");if(f.current!==a)throw Error("You should not modify the loadMore of options");s.current=u,f.current=a;var l,d=function(){return fetch.apply(void 0,arguments).then((function(t){if(t.ok)return t.json();throw new Error(t.statusText)}))},h=c||d;if("string"==typeof t)l=function(){return h(t)};else if("object"==typeof t){var v=t.url,p=r(t,["url"]);l=function(){return c?c(t):d(v,p)}}else l=function(){for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];return new Promise((function(e,i){var o=t.apply(void 0,n);if(o.then)o.then((function(t){return e(t)})).catch((function(t){return i(t)}));else if("string"==typeof o)h(o).then((function(t){e(t)})).catch((function(t){return i(t)}));else if("object"==typeof o)if(c)c(o).then((function(t){e(t)})).catch((function(t){return i(t)}));else{var u=o.url,a=r(o,["url"]);d(u,a).then((function(t){e(t)})).catch((function(t){return i(t)}))}}))};return a?E(l,o):u?S(l,o):T(l,o)}}])})); | ||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("React")):"function"==typeof define&&define.amd?define(["React"],e):"object"==typeof exports?exports.ahooksUseRequest=e(require("React")):t.ahooksUseRequest=e(t.React)}(this,(function(t){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=4)}([function(e,n){e.exports=t},function(t,e){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){(function(e){var n=/^\s+|\s+$/g,r=/^[-+]0x[0-9a-f]+$/i,i=/^0b[01]+$/i,o=/^0o[0-7]+$/i,u=parseInt,a="object"==typeof e&&e&&e.Object===Object&&e,c="object"==typeof self&&self&&self.Object===Object&&self,s=a||c||Function("return this")(),f=Object.prototype.toString,l=Math.max,d=Math.min,h=function(){return s.Date.now()};function v(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function p(t){if("number"==typeof t)return t;if(function(t){return"symbol"==typeof t||function(t){return!!t&&"object"==typeof t}(t)&&"[object Symbol]"==f.call(t)}(t))return NaN;if(v(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=v(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(n,"");var a=i.test(t);return a||o.test(t)?u(t.slice(2),a?2:8):r.test(t)?NaN:+t}t.exports=function(t,e,n){var r,i,o,u,a,c,s=0,f=!1,g=!1,b=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function y(e){var n=r,o=i;return r=i=void 0,s=e,u=t.apply(o,n)}function m(t){return s=t,a=setTimeout(j,e),f?y(t):u}function O(t){var n=t-c;return void 0===c||n>=e||n<0||g&&t-s>=o}function j(){var t=h();if(O(t))return w(t);a=setTimeout(j,function(t){var n=e-(t-c);return g?d(n,o-(t-s)):n}(t))}function w(t){return a=void 0,b&&r?y(t):(r=i=void 0,u)}function T(){var t=h(),n=O(t);if(r=arguments,i=this,c=t,n){if(void 0===a)return m(c);if(g)return a=setTimeout(j,e),y(c)}return void 0===a&&(a=setTimeout(j,e)),u}return e=p(e)||0,v(n)&&(f=!!n.leading,o=(g="maxWait"in n)?l(p(n.maxWait)||0,e):o,b="trailing"in n?!!n.trailing:b),T.cancel=function(){void 0!==a&&clearTimeout(a),s=0,r=c=i=a=void 0},T.flush=function(){return void 0===a?u:w(h())},T}}).call(this,n(1))},function(t,e,n){(function(e){var n=/^\s+|\s+$/g,r=/^[-+]0x[0-9a-f]+$/i,i=/^0b[01]+$/i,o=/^0o[0-7]+$/i,u=parseInt,a="object"==typeof e&&e&&e.Object===Object&&e,c="object"==typeof self&&self&&self.Object===Object&&self,s=a||c||Function("return this")(),f=Object.prototype.toString,l=Math.max,d=Math.min,h=function(){return s.Date.now()};function v(t,e,n){var r,i,o,u,a,c,s=0,f=!1,v=!1,b=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function y(e){var n=r,o=i;return r=i=void 0,s=e,u=t.apply(o,n)}function m(t){return s=t,a=setTimeout(j,e),f?y(t):u}function O(t){var n=t-c;return void 0===c||n>=e||n<0||v&&t-s>=o}function j(){var t=h();if(O(t))return w(t);a=setTimeout(j,function(t){var n=e-(t-c);return v?d(n,o-(t-s)):n}(t))}function w(t){return a=void 0,b&&r?y(t):(r=i=void 0,u)}function T(){var t=h(),n=O(t);if(r=arguments,i=this,c=t,n){if(void 0===a)return m(c);if(v)return a=setTimeout(j,e),y(c)}return void 0===a&&(a=setTimeout(j,e)),u}return e=g(e)||0,p(n)&&(f=!!n.leading,o=(v="maxWait"in n)?l(g(n.maxWait)||0,e):o,b="trailing"in n?!!n.trailing:b),T.cancel=function(){void 0!==a&&clearTimeout(a),s=0,r=c=i=a=void 0},T.flush=function(){return void 0===a?u:w(h())},T}function p(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function g(t){if("number"==typeof t)return t;if(function(t){return"symbol"==typeof t||function(t){return!!t&&"object"==typeof t}(t)&&"[object Symbol]"==f.call(t)}(t))return NaN;if(p(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=p(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(n,"");var a=i.test(t);return a||o.test(t)?u(t.slice(2),a?2:8):r.test(t)?NaN:+t}t.exports=function(t,e,n){var r=!0,i=!0;if("function"!=typeof t)throw new TypeError("Expected a function");return p(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),v(t,e,{leading:r,maxWait:e,trailing:i})}}).call(this,n(1))},function(t,e,n){"use strict";n.r(e),n.d(e,"useAsync",(function(){return E})),n.d(e,"usePaginated",(function(){return R})),n.d(e,"useLoadMore",(function(){return S})),n.d(e,"UseRequestProvider",(function(){return P})),n.d(e,"UseAPIProvider",(function(){return M}));function r(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]])}return n}var i=n(0),o=n.n(i),u=n(2),a=n.n(u),c=n(3),s=n.n(c);function f(){return"undefined"==typeof document||void 0===document.visibilityState||"hidden"!==document.visibilityState}var l=new Map,d=function(t){var e=l.get(t);return{data:null==e?void 0:e.data,startTime:null==e?void 0:e.startTime}};var h=function(t){var e=Object(i.useRef)((function(){throw new Error("Cannot call an event handler while rendering.")}));e.current=t;var n=Object(i.useCallback)((function(){var t=e.current;if(t)return t.apply(void 0,arguments)}),[e]);if("function"==typeof t)return n},v=function(t,e){var n=Object(i.useRef)(!1);Object(i.useEffect)((function(){if(n.current)return t();n.current=!0}),e)},p=[];var g=!1;if("undefined"!=typeof window&&window.addEventListener&&!g){var b=function(){if(f()&&(void 0===navigator.onLine||navigator.onLine))for(var t=0;t<p.length;t++){(0,p[t])()}};window.addEventListener("visibilitychange",b,!1),window.addEventListener("focus",b,!1),g=!0}var y=function(t){return p.push(t),function(){var e=p.indexOf(t);p.splice(e,1)}},m=[];var O=!1;if("undefined"!=typeof window&&window.addEventListener&&!O){window.addEventListener("visibilitychange",(function(){if(f())for(var t=0;t<m.length;t++){(0,m[t])()}}),!1),O=!0}var j=function(t){return m.push(t),function(){var e=m.indexOf(t);m.splice(e,1)}},w="AHOOKS_USE_REQUEST_DEFAULT_KEY",T=function(){function t(t,e,n,r){var i,o,u;this.count=0,this.unmountedFlag=!1,this.pollingWhenVisibleFlag=!1,this.pollingTimer=void 0,this.loadingDelayTimer=void 0,this.unsubscribe=[],this.that=this,this.state={loading:!1,params:[],data:void 0,error:void 0,run:this.run.bind(this.that),mutate:this.mutate.bind(this.that),refresh:this.refresh.bind(this.that),cancel:this.cancel.bind(this.that),unmount:this.unmount.bind(this.that)},this.service=t,this.config=e,this.subscribe=n,r&&(this.state=Object.assign(Object.assign({},this.state),r)),this.debounceRun=this.config.debounceInterval?a()(this._run,this.config.debounceInterval):void 0,this.throttleRun=this.config.throttleInterval?s()(this._run,this.config.throttleInterval):void 0,this.limitRefresh=(i=this.refresh.bind(this),o=this.config.focusTimespan,u=!1,function(){u||(u=!0,i.apply(void 0,arguments),setTimeout((function(){u=!1}),o))}),this.config.pollingInterval&&this.unsubscribe.push(j(this.rePolling.bind(this))),this.config.refreshOnWindowFocus&&this.unsubscribe.push(y(this.limitRefresh.bind(this)))}var e=t.prototype;return e.setState=function(t){void 0===t&&(t={}),this.state=Object.assign(Object.assign({},this.state),t),this.subscribe(this.state)},e._run=function(){for(var t=this,e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];this.pollingTimer&&clearTimeout(this.pollingTimer),this.loadingDelayTimer&&clearTimeout(this.loadingDelayTimer),this.count+=1;var i=this.count;return this.setState({loading:!this.config.loadingDelay,params:n}),this.config.loadingDelay&&(this.loadingDelayTimer=setTimeout((function(){t.setState({loading:!0})}),this.config.loadingDelay)),this.service.apply(this,n).then((function(e){if(!t.unmountedFlag&&i===t.count){t.loadingDelayTimer&&clearTimeout(t.loadingDelayTimer);var r=t.config.formatResult?t.config.formatResult(e):e;return t.setState({data:r,error:void 0,loading:!1}),t.config.onSuccess&&t.config.onSuccess(r,n),r}})).catch((function(e){if(!t.unmountedFlag&&i===t.count){if(t.loadingDelayTimer&&clearTimeout(t.loadingDelayTimer),t.setState({data:void 0,error:e,loading:!1}),t.config.onError&&t.config.onError(e,n),t.config.throwOnError)throw e;return console.error(e),Promise.reject("useRequest has caught the exception, if you need to handle the exception yourself, you can set options.throwOnError to true.")}})).finally((function(){if(!t.unmountedFlag&&i===t.count&&t.config.pollingInterval){if(!f()&&!t.config.pollingWhenHidden)return void(t.pollingWhenVisibleFlag=!0);t.pollingTimer=setTimeout((function(){t._run.apply(t,n)}),t.config.pollingInterval)}}))},e.run=function(){return this.debounceRun?(this.debounceRun.apply(this,arguments),Promise.resolve(null)):this.throttleRun?(this.throttleRun.apply(this,arguments),Promise.resolve(null)):this._run.apply(this,arguments)},e.cancel=function(){this.debounceRun&&this.debounceRun.cancel(),this.throttleRun&&this.throttleRun.cancel(),this.loadingDelayTimer&&clearTimeout(this.loadingDelayTimer),this.pollingTimer&&clearTimeout(this.pollingTimer),this.pollingWhenVisibleFlag=!1,this.count+=1,this.setState({loading:!1})},e.refresh=function(){return this.run.apply(this,this.state.params)},e.rePolling=function(){this.pollingWhenVisibleFlag&&(this.pollingWhenVisibleFlag=!1,this.refresh())},e.mutate=function(t){"function"==typeof t?this.setState({data:t(this.state.data)||{}}):this.setState({data:t})},e.unmount=function(){this.unmountedFlag=!0,this.cancel(),this.unsubscribe.forEach((function(t){t()}))},t}();var E=function(t,e){var n,r=e||{},o=r.refreshDeps,u=void 0===o?[]:o,a=r.manual,c=void 0!==a&&a,s=r.onSuccess,f=void 0===s?function(){}:s,p=r.onError,g=void 0===p?function(){}:p,b=r.defaultLoading,y=void 0!==b&&b,m=r.loadingDelay,O=r.pollingInterval,j=void 0===O?0:O,E=r.pollingWhenHidden,S=void 0===E||E,R=r.defaultParams,x=void 0===R?[]:R,D=r.refreshOnWindowFocus,P=void 0!==D&&D,M=r.focusTimespan,C=void 0===M?5e3:M,F=r.fetchKey,k=r.cacheKey,I=r.cacheTime,W=void 0===I?3e5:I,_=r.staleTime,K=void 0===_?0:_,L=r.debounceInterval,N=r.throttleInterval,q=r.initialData,z=r.ready,U=void 0===z||z,$=r.throwOnError,A=void 0!==$&&$,H=Object(i.useRef)(w),V=h(t),Y=h(f),Q=h(g),B=h(F);"formatResult"in r&&(n=r.formatResult);var G={formatResult:h(n),onSuccess:Y,onError:Q,loadingDelay:m,pollingInterval:j,pollingWhenHidden:S,refreshOnWindowFocus:P,focusTimespan:C,debounceInterval:L,throttleInterval:N,throwOnError:A},J=h((function(t,e){tt((function(n){return n[t]=e,Object.assign({},n)}))})),X=Object(i.useState)((function(){var t;if(k){var e=null===(t=d(k))||void 0===t?void 0:t.data;if(e){H.current=e.newstFetchKey;var n={};return Object.keys(e.fetches).forEach((function(t){var r=e.fetches[t],i=new T(V,G,J.bind(null,t),{loading:r.loading,params:r.params,data:r.data,error:r.error});n[t]=i.state})),n}}return[]})),Z=X[0],tt=X[1],et=Object(i.useRef)(Z);et.current=Z;var nt=Object(i.useRef)(),rt=Object(i.useCallback)((function(){for(var t,e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];if(U){if(B){var i=B.apply(void 0,n);H.current=void 0===i?w:i}var o=H.current,u=et.current[o];if(!u){var a=new T(V,G,J.bind(null,o),{data:q});u=a.state,tt((function(t){return t[o]=u,Object.assign({},t)}))}return(t=u).run.apply(t,n)}nt.current=n}),[F,J,U]),it=Object(i.useRef)(rt);it.current=rt,v((function(){k&&function(t,e,n){var r,i=l.get(t);(null==i?void 0:i.timer)&&clearTimeout(i.timer),e>-1&&(r=setTimeout((function(){l.delete(t)}),e)),l.set(t,{data:n,timer:r,startTime:(new Date).getTime()})}(k,W,{fetches:Z,newstFetchKey:H.current})}),[k,Z]);var ot=Object(i.useRef)(!1);v((function(){U&&(!ot.current&&nt.current&&it.current.apply(it,nt.current),ot.current=!0)}),[U]),Object(i.useEffect)((function(){var t;if(!c)if(Object.keys(Z).length>0){var e=(null===(t=d(k))||void 0===t?void 0:t.startTime)||0;-1===K||(new Date).getTime()-e<=K||Object.values(Z).forEach((function(t){t.refresh()}))}else it.current.apply(it,x)}),[]);var ut=Object(i.useCallback)((function(){Object.values(et.current).forEach((function(t){t.unmount()})),H.current=w,tt({}),et.current={}}),[tt]);v((function(){c||Object.values(et.current).forEach((function(t){t.refresh()}))}),[].concat(u)),Object(i.useEffect)((function(){return function(){Object.values(et.current).forEach((function(t){t.unmount()}))}}),[]);var at=Object(i.useCallback)((function(t){return function(){throw new Error("Cannot call "+t+" when service not executed once.")}}),[]);return Object.assign(Object.assign({loading:U&&!c||y,data:q,error:void 0,params:[],cancel:at("cancel"),refresh:at("refresh"),mutate:at("mutate")},Z[H.current]||{}),{run:rt,fetches:Z,reset:ut})};var S=function(t,e){var n=e.refreshDeps,o=void 0===n?[]:n,u=e.ref,a=e.isNoMore,c=e.threshold,s=void 0===c?100:c,f=(e.fetchKey,r(e,["refreshDeps","ref","isNoMore","threshold","fetchKey"])),l=Object(i.useState)(!1),d=l[0],h=l[1];Object(i.useEffect)((function(){e.fetchKey&&console.warn("useRequest loadMore mode don't need fetchKey!")}),[]);var p=E(t,Object.assign(Object.assign({},f),{fetchKey:function(t){var e;return(null===(e=null==t?void 0:t.list)||void 0===e?void 0:e.length)||0},onSuccess:function(){h(!1),e.onSuccess&&e.onSuccess.apply(e,arguments)}})),g=p.data,b=p.run,y=p.params,m=p.reset,O=p.loading,j=p.fetches,w=Object(i.useCallback)((function(){m();var t=y.slice(1);b.apply(void 0,[void 0].concat(t))}),[b,m,y]),T=Object(i.useRef)(w);T.current=w,v((function(){e.manual||T.current()}),[].concat(o));var S=Object(i.useMemo)((function(){var t=[],e=g;return Object.values(j).forEach((function(n){var r,i;(null===(r=n.data)||void 0===r?void 0:r.list)&&(t=t.concat(null===(i=n.data)||void 0===i?void 0:i.list)),n.loading||(e=n.data)})),Object.assign(Object.assign({},e),{list:t})}),[j,g]),R=!!a&&(!O&&!d&&a(S)),x=Object(i.useCallback)((function(){if(!R){h(!0);var t=y.slice(1);b.apply(void 0,[S].concat(t))}}),[R,b,S,y]),D=Object(i.useCallback)((function(){!O&&!d&&u&&u.current&&u.current.scrollHeight-u.current.scrollTop<=u.current.clientHeight+s&&x()}),[O,u,x]);return Object(i.useEffect)((function(){return u&&u.current?(u.current.addEventListener("scroll",D),function(){u&&u.current&&u.current.removeEventListener("scroll",D)}):function(){}}),[D]),Object.assign(Object.assign({},p),{data:S,reload:w,loading:O&&0===S.list.length,loadMore:x,loadingMore:d,noMore:R})};var R=function(t,e){e.paginated;var n=e.defaultPageSize,o=void 0===n?10:n,u=e.refreshDeps,a=void 0===u?[]:u,c=e.fetchKey,s=r(e,["paginated","defaultPageSize","refreshDeps","fetchKey"]);Object(i.useEffect)((function(){c&&console.error("useRequest pagination's fetchKey will not work!")}),[]);var f=E(t,Object.assign({defaultParams:[{current:1,pageSize:o}]},s)),l=f.data,d=f.params,h=f.run,p=f.loading,g=r(f,["data","params","run","loading"]),b=d&&d[0]?d[0]:{},y=b.current,m=void 0===y?1:y,O=b.pageSize,j=void 0===O?o:O,w=b.sorter,T=void 0===w?{}:w,S=b.filters,R=void 0===S?{}:S,x=Object(i.useCallback)((function(t){var e=d[0],n=d.slice(1);h.apply(void 0,[Object.assign(Object.assign({},e),t)].concat(n))}),[h,d]),D=(null==l?void 0:l.total)||0,P=Object(i.useMemo)((function(){return Math.ceil(D/j)}),[j,D]),M=Object(i.useCallback)((function(t,e){var n=t<=0?1:t,r=e<=0?1:e,i=Math.ceil(D/r);n>i&&(n=i),x({current:t,pageSize:e})}),[D,x]),C=Object(i.useCallback)((function(t){M(t,j)}),[M,j]),F=Object(i.useCallback)((function(t){M(m,t)}),[M,m]),k=Object(i.useRef)(C);k.current=C,v((function(){e.manual||k.current(1)}),[].concat(a));var I=Object(i.useCallback)((function(t,e,n){x({current:t.current,pageSize:t.pageSize||o,filters:e,sorter:n})}),[R,T,x]);return Object.assign({loading:p,data:l,params:d,run:h,pagination:{current:m,pageSize:j,total:D,totalPage:P,onChange:M,changeCurrent:C,changePageSize:F},tableProps:{dataSource:(null==l?void 0:l.list)||[],loading:p,onChange:I,pagination:{current:m,pageSize:j,total:D}},sorter:T,filters:R},g)},x=o.a.createContext({});x.displayName="UseRequestConfigContext";var D=x;var P=D.Provider,M=P;e.default=function(t,e){void 0===e&&(e={});var n=Object(i.useContext)(D),o=Object.assign(Object.assign({},n),e),u=o.paginated,a=o.loadMore,c=o.requestMethod,s=Object(i.useRef)(u),f=Object(i.useRef)(a);if(s.current!==u)throw Error("You should not modify the paginated of options");if(f.current!==a)throw Error("You should not modify the loadMore of options");s.current=u,f.current=a;var l,d=function(){return fetch.apply(void 0,arguments).then((function(t){if(t.ok)return t.json();throw new Error(t.statusText)}))},h=c||d;if("string"==typeof t)l=function(){return h(t)};else if("object"==typeof t){var v=t.url,p=r(t,["url"]);l=function(){return c?c(t):d(v,p)}}else l=function(){for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];return new Promise((function(e,i){var o=t.apply(void 0,n);if(o.then)o.then((function(t){return e(t)})).catch((function(t){return i(t)}));else if("string"==typeof o)h(o).then((function(t){e(t)})).catch((function(t){return i(t)}));else if("object"==typeof o)if(c)c(o).then((function(t){e(t)})).catch((function(t){return i(t)}));else{var u=o.url,a=r(o,["url"]);d(u,a).then((function(t){e(t)})).catch((function(t){return i(t)}))}}))};return a?S(l,o):u?R(l,o):E(l,o)}}])})); |
import { DependencyList, RefObject } from 'react'; | ||
import { PaginationConfig, Filter, Sorter } from './antdTypes'; | ||
import { cachedKeyType } from './utils/cache'; | ||
import { CachedKeyType } from './utils/cache'; | ||
export declare type noop = (...args: any[]) => void; | ||
@@ -60,3 +60,5 @@ export declare type Service<R, P extends any[]> = (...args: P) => Promise<R>; | ||
focusTimespan?: number; | ||
cacheKey?: cachedKeyType; | ||
cacheKey?: CachedKeyType; | ||
cacheTime?: number; | ||
staleTime?: number; | ||
debounceInterval?: number; | ||
@@ -63,0 +65,0 @@ throttleInterval?: number; |
@@ -143,3 +143,5 @@ import debounce from 'lodash.debounce'; | ||
console.error(error); | ||
console.error(error); // eslint-disable-next-line prefer-promise-reject-errors | ||
return Promise.reject('useRequest has caught the exception, if you need to handle the exception yourself, you can set options.throwOnError to true.'); | ||
} | ||
@@ -263,2 +265,6 @@ })["finally"](function () { | ||
cacheKey = _options.cacheKey, | ||
_options$cacheTime = _options.cacheTime, | ||
cacheTime = _options$cacheTime === void 0 ? 5 * 60 * 1000 : _options$cacheTime, | ||
_options$staleTime = _options.staleTime, | ||
staleTime = _options$staleTime === void 0 ? 0 : _options$staleTime, | ||
debounceInterval = _options.debounceInterval, | ||
@@ -307,13 +313,15 @@ throttleInterval = _options.throttleInterval, | ||
var _useState = useState(function () { | ||
// 如果有 缓存,则从缓存中读数据 | ||
var _a; // 如果有 缓存,则从缓存中读数据 | ||
if (cacheKey) { | ||
var cache = getCache(cacheKey); | ||
var cacheData = (_a = getCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data; | ||
if (cache) { | ||
newstFetchKey.current = cache.newstFetchKey; | ||
if (cacheData) { | ||
newstFetchKey.current = cacheData.newstFetchKey; | ||
/* 使用 initState, 重新 new Fetch */ | ||
var newFetches = {}; | ||
Object.keys(cache.fetches).forEach(function (key) { | ||
var cacheFetch = cache.fetches[key]; | ||
Object.keys(cacheData.fetches).forEach(function (key) { | ||
var cacheFetch = cacheData.fetches[key]; | ||
var newFetch = new Fetch(servicePersist, config, subscribe.bind(null, key), { | ||
@@ -379,5 +387,5 @@ loading: cacheFetch.loading, | ||
useEffect(function () { | ||
useUpdateEffect(function () { | ||
if (cacheKey) { | ||
setCache(cacheKey, { | ||
setCache(cacheKey, cacheTime, { | ||
fetches: fetches, | ||
@@ -401,9 +409,17 @@ newstFetchKey: newstFetchKey.current | ||
useEffect(function () { | ||
var _a; | ||
if (!manual) { | ||
// 如果有缓存 | ||
// 如果有缓存,则重新请求 | ||
if (Object.keys(fetches).length > 0) { | ||
/* 重新执行所有的 */ | ||
Object.values(fetches).forEach(function (f) { | ||
f.refresh(); | ||
}); | ||
// 如果 staleTime 是 -1,则 cache 永不过期 | ||
// 如果 statleTime 超期了,则重新请求 | ||
var cacheStartTime = ((_a = getCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.startTime) || 0; | ||
if (!(staleTime === -1 || new Date().getTime() - cacheStartTime <= staleTime)) { | ||
/* 重新执行所有的 cache */ | ||
Object.values(fetches).forEach(function (f) { | ||
f.refresh(); | ||
}); | ||
} | ||
} else { | ||
@@ -410,0 +426,0 @@ // 第一次默认执行,可以通过 defaultParams 设置参数 |
@@ -1,4 +0,12 @@ | ||
export declare type cachedKeyType = string | number; | ||
declare const setCache: (key: cachedKeyType, data: any) => void; | ||
declare const getCache: (key: cachedKeyType) => any; | ||
export declare type CachedKeyType = string | number; | ||
export declare type cachedData = { | ||
data: any; | ||
timer: ReturnType<typeof setTimeout>; | ||
startTime: number; | ||
}; | ||
declare const setCache: (key: CachedKeyType, cacheTime: number, data: any) => void; | ||
declare const getCache: (key: CachedKeyType) => { | ||
data: any; | ||
startTime: number; | ||
}; | ||
export { getCache, setCache }; |
@@ -1,24 +0,34 @@ | ||
var cache = {}; | ||
var cache = new Map(); | ||
var setCache = function setCache(key, data) { | ||
if (cache[key]) { | ||
clearTimeout(cache[key].timer); | ||
} // 数据在不活跃 5min 后,删除掉 | ||
var setCache = function setCache(key, cacheTime, data) { | ||
var currentCache = cache.get(key); | ||
if (currentCache === null || currentCache === void 0 ? void 0 : currentCache.timer) { | ||
clearTimeout(currentCache.timer); | ||
} | ||
var timer = setTimeout(function () { | ||
delete cache[key]; | ||
}, 5 * 60 * 1000); | ||
cache[key] = { | ||
var timer; | ||
if (cacheTime > -1) { | ||
// 数据在不活跃 cacheTime 后,删除掉 | ||
timer = setTimeout(function () { | ||
cache["delete"](key); | ||
}, cacheTime); | ||
} | ||
cache.set(key, { | ||
data: data, | ||
timer: timer | ||
}; | ||
timer: timer, | ||
startTime: new Date().getTime() | ||
}); | ||
}; | ||
var getCache = function getCache(key) { | ||
var _a; | ||
return (_a = cache[key]) === null || _a === void 0 ? void 0 : _a.data; | ||
var currentCache = cache.get(key); | ||
return { | ||
data: currentCache === null || currentCache === void 0 ? void 0 : currentCache.data, | ||
startTime: currentCache === null || currentCache === void 0 ? void 0 : currentCache.startTime | ||
}; | ||
}; | ||
export { getCache, setCache }; |
import { DependencyList, RefObject } from 'react'; | ||
import { PaginationConfig, Filter, Sorter } from './antdTypes'; | ||
import { cachedKeyType } from './utils/cache'; | ||
import { CachedKeyType } from './utils/cache'; | ||
export declare type noop = (...args: any[]) => void; | ||
@@ -60,3 +60,5 @@ export declare type Service<R, P extends any[]> = (...args: P) => Promise<R>; | ||
focusTimespan?: number; | ||
cacheKey?: cachedKeyType; | ||
cacheKey?: CachedKeyType; | ||
cacheTime?: number; | ||
staleTime?: number; | ||
debounceInterval?: number; | ||
@@ -63,0 +65,0 @@ throttleInterval?: number; |
@@ -161,3 +161,5 @@ "use strict"; | ||
console.error(error); | ||
console.error(error); // eslint-disable-next-line prefer-promise-reject-errors | ||
return Promise.reject('useRequest has caught the exception, if you need to handle the exception yourself, you can set options.throwOnError to true.'); | ||
} | ||
@@ -281,2 +283,6 @@ })["finally"](function () { | ||
cacheKey = _options.cacheKey, | ||
_options$cacheTime = _options.cacheTime, | ||
cacheTime = _options$cacheTime === void 0 ? 5 * 60 * 1000 : _options$cacheTime, | ||
_options$staleTime = _options.staleTime, | ||
staleTime = _options$staleTime === void 0 ? 0 : _options$staleTime, | ||
debounceInterval = _options.debounceInterval, | ||
@@ -325,13 +331,15 @@ throttleInterval = _options.throttleInterval, | ||
var _react_1$useState = react_1.useState(function () { | ||
// 如果有 缓存,则从缓存中读数据 | ||
var _a; // 如果有 缓存,则从缓存中读数据 | ||
if (cacheKey) { | ||
var cache = cache_1.getCache(cacheKey); | ||
var cacheData = (_a = cache_1.getCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data; | ||
if (cache) { | ||
newstFetchKey.current = cache.newstFetchKey; | ||
if (cacheData) { | ||
newstFetchKey.current = cacheData.newstFetchKey; | ||
/* 使用 initState, 重新 new Fetch */ | ||
var newFetches = {}; | ||
Object.keys(cache.fetches).forEach(function (key) { | ||
var cacheFetch = cache.fetches[key]; | ||
Object.keys(cacheData.fetches).forEach(function (key) { | ||
var cacheFetch = cacheData.fetches[key]; | ||
var newFetch = new Fetch(servicePersist, config, subscribe.bind(null, key), { | ||
@@ -397,5 +405,5 @@ loading: cacheFetch.loading, | ||
react_1.useEffect(function () { | ||
useUpdateEffect_1["default"](function () { | ||
if (cacheKey) { | ||
cache_1.setCache(cacheKey, { | ||
cache_1.setCache(cacheKey, cacheTime, { | ||
fetches: fetches, | ||
@@ -419,9 +427,17 @@ newstFetchKey: newstFetchKey.current | ||
react_1.useEffect(function () { | ||
var _a; | ||
if (!manual) { | ||
// 如果有缓存 | ||
// 如果有缓存,则重新请求 | ||
if (Object.keys(fetches).length > 0) { | ||
/* 重新执行所有的 */ | ||
Object.values(fetches).forEach(function (f) { | ||
f.refresh(); | ||
}); | ||
// 如果 staleTime 是 -1,则 cache 永不过期 | ||
// 如果 statleTime 超期了,则重新请求 | ||
var cacheStartTime = ((_a = cache_1.getCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.startTime) || 0; | ||
if (!(staleTime === -1 || new Date().getTime() - cacheStartTime <= staleTime)) { | ||
/* 重新执行所有的 cache */ | ||
Object.values(fetches).forEach(function (f) { | ||
f.refresh(); | ||
}); | ||
} | ||
} else { | ||
@@ -428,0 +444,0 @@ // 第一次默认执行,可以通过 defaultParams 设置参数 |
@@ -1,4 +0,12 @@ | ||
export declare type cachedKeyType = string | number; | ||
declare const setCache: (key: cachedKeyType, data: any) => void; | ||
declare const getCache: (key: cachedKeyType) => any; | ||
export declare type CachedKeyType = string | number; | ||
export declare type cachedData = { | ||
data: any; | ||
timer: ReturnType<typeof setTimeout>; | ||
startTime: number; | ||
}; | ||
declare const setCache: (key: CachedKeyType, cacheTime: number, data: any) => void; | ||
declare const getCache: (key: CachedKeyType) => { | ||
data: any; | ||
startTime: number; | ||
}; | ||
export { getCache, setCache }; |
@@ -7,17 +7,25 @@ "use strict"; | ||
exports.setCache = exports.getCache = void 0; | ||
var cache = {}; | ||
var cache = new Map(); | ||
var setCache = function setCache(key, data) { | ||
if (cache[key]) { | ||
clearTimeout(cache[key].timer); | ||
} // 数据在不活跃 5min 后,删除掉 | ||
var setCache = function setCache(key, cacheTime, data) { | ||
var currentCache = cache.get(key); | ||
if (currentCache === null || currentCache === void 0 ? void 0 : currentCache.timer) { | ||
clearTimeout(currentCache.timer); | ||
} | ||
var timer = setTimeout(function () { | ||
delete cache[key]; | ||
}, 5 * 60 * 1000); | ||
cache[key] = { | ||
var timer; | ||
if (cacheTime > -1) { | ||
// 数据在不活跃 cacheTime 后,删除掉 | ||
timer = setTimeout(function () { | ||
cache["delete"](key); | ||
}, cacheTime); | ||
} | ||
cache.set(key, { | ||
data: data, | ||
timer: timer | ||
}; | ||
timer: timer, | ||
startTime: new Date().getTime() | ||
}); | ||
}; | ||
@@ -28,7 +36,9 @@ | ||
var getCache = function getCache(key) { | ||
var _a; | ||
return (_a = cache[key]) === null || _a === void 0 ? void 0 : _a.data; | ||
var currentCache = cache.get(key); | ||
return { | ||
data: currentCache === null || currentCache === void 0 ? void 0 : currentCache.data, | ||
startTime: currentCache === null || currentCache === void 0 ? void 0 : currentCache.startTime | ||
}; | ||
}; | ||
exports.getCache = getCache; |
{ | ||
"name": "@ahooksjs/use-request", | ||
"version": "2.0.1", | ||
"version": "2.0.2", | ||
"description": "React Hooks for fetching, caching and updating asynchronous data", | ||
@@ -5,0 +5,0 @@ "main": "./lib/index.js", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No README
QualityPackage does not have a README. This may indicate a failed publish or a low quality package.
Found 1 instance in 1 package
108360
63
2287
0
48
7