@ahooksjs/use-request
Advanced tools
Comparing version 1.0.0 to 1.0.1-beta.1
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("React")):"function"==typeof define&&define.amd?define(["React"],t):"object"==typeof exports?exports.ahooksUseRequest=t(require("React")):e.ahooksUseRequest=t(e.React)}(this,(function(e){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=4)}([function(t,n){t.exports=e},function(e,t){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"===("undefined"==typeof window?"undefined":n(window))&&(r=window)}e.exports=r},function(e,t,n){(function(t){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var r=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,o=/^0b[01]+$/i,u=/^0o[0-7]+$/i,c=parseInt,a="object"==(void 0===t?"undefined":n(t))&&t&&t.Object===Object&&t,f="object"==("undefined"==typeof self?"undefined":n(self))&&self&&self.Object===Object&&self,s=a||f||Function("return this")(),l=Object.prototype.toString,d=Math.max,h=Math.min,p=function(){return s.Date.now()};function b(e){var t=n(e);return!!e&&("object"==t||"function"==t)}function v(e){return"symbol"==n(e)||function(e){return!!e&&"object"==n(e)}(e)&&"[object Symbol]"==l.call(e)}function y(e){if("number"==typeof e)return e;if(v(e))return NaN;if(b(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=b(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(r,"");var n=o.test(e);return n||u.test(e)?c(e.slice(2),n?2:8):i.test(e)?NaN:+e}e.exports=function(e,t,n){var r,i,o,u,c,a,f=0,s=!1,l=!1,v=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function g(t){var n=r,o=i;return r=i=void 0,f=t,u=e.apply(o,n)}function m(e){return f=e,c=setTimeout(j,t),s?g(e):u}function O(e){var n=e-a;return void 0===a||n>=t||n<0||l&&e-f>=o}function j(){var e=p();if(O(e))return w(e);c=setTimeout(j,function(e){var n=t-(e-a);return l?h(n,o-(e-f)):n}(e))}function w(e){return c=void 0,v&&r?g(e):(r=i=void 0,u)}function S(){var e=p(),n=O(e);if(r=arguments,i=this,a=e,n){if(void 0===c)return m(a);if(l)return c=setTimeout(j,t),g(a)}return void 0===c&&(c=setTimeout(j,t)),u}return t=y(t)||0,b(n)&&(s=!!n.leading,o=(l="maxWait"in n)?d(y(n.maxWait)||0,t):o,v="trailing"in n?!!n.trailing:v),S.cancel=function(){void 0!==c&&clearTimeout(c),f=0,r=a=i=c=void 0},S.flush=function(){return void 0===c?u:w(p())},S}}).call(this,n(1))},function(e,t,n){(function(t){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var r=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,o=/^0b[01]+$/i,u=/^0o[0-7]+$/i,c=parseInt,a="object"==(void 0===t?"undefined":n(t))&&t&&t.Object===Object&&t,f="object"==("undefined"==typeof self?"undefined":n(self))&&self&&self.Object===Object&&self,s=a||f||Function("return this")(),l=Object.prototype.toString,d=Math.max,h=Math.min,p=function(){return s.Date.now()};function b(e,t,n){var r,i,o,u,c,a,f=0,s=!1,l=!1,b=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function y(t){var n=r,o=i;return r=i=void 0,f=t,u=e.apply(o,n)}function m(e){return f=e,c=setTimeout(j,t),s?y(e):u}function O(e){var n=e-a;return void 0===a||n>=t||n<0||l&&e-f>=o}function j(){var e=p();if(O(e))return w(e);c=setTimeout(j,function(e){var n=t-(e-a);return l?h(n,o-(e-f)):n}(e))}function w(e){return c=void 0,b&&r?y(e):(r=i=void 0,u)}function S(){var e=p(),n=O(e);if(r=arguments,i=this,a=e,n){if(void 0===c)return m(a);if(l)return c=setTimeout(j,t),y(a)}return void 0===c&&(c=setTimeout(j,t)),u}return t=g(t)||0,v(n)&&(s=!!n.leading,o=(l="maxWait"in n)?d(g(n.maxWait)||0,t):o,b="trailing"in n?!!n.trailing:b),S.cancel=function(){void 0!==c&&clearTimeout(c),f=0,r=a=i=c=void 0},S.flush=function(){return void 0===c?u:w(p())},S}function v(e){var t=n(e);return!!e&&("object"==t||"function"==t)}function y(e){return"symbol"==n(e)||function(e){return!!e&&"object"==n(e)}(e)&&"[object Symbol]"==l.call(e)}function g(e){if("number"==typeof e)return e;if(y(e))return NaN;if(v(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=v(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(r,"");var n=o.test(e);return n||u.test(e)?c(e.slice(2),n?2:8):i.test(e)?NaN:+e}e.exports=function(e,t,n){var r=!0,i=!0;if("function"!=typeof e)throw new TypeError("Expected a function");return v(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),b(e,t,{leading:r,maxWait:t,trailing:i})}}).call(this,n(1))},function(e,t,n){"use strict";n.r(t),n.d(t,"useAsync",(function(){return E})),n.d(t,"usePaginated",(function(){return W})),n.d(t,"useLoadMore",(function(){return x})),n.d(t,"UseRequestProvider",(function(){return z}));var r=n(0),i=n.n(r),o=n(2),u=n.n(o),c=n(3),a=n.n(c);function f(){return"undefined"==typeof document||void 0===document.visibilityState||"hidden"!==document.visibilityState}var s={};var l=function(e,t){void 0===t&&(t=[]);var n=Object(r.useRef)((function(){throw new Error("Cannot call an event handler while rendering.")}));Object(r.useEffect)((function(){n.current=e}),[e].concat(t));var i=Object(r.useCallback)((function(){var e=n.current;if(e)return e.apply(void 0,arguments)}),[n]);if("function"==typeof e)return i},d=function(e,t){var n=Object(r.useRef)(!1);Object(r.useEffect)((function(){if(n.current)return e();n.current=!0}),t)},h=[];var p=!1;if("undefined"!=typeof window&&window.addEventListener&&!p){var b=function(){if(f()&&(void 0===navigator.onLine||navigator.onLine))for(var e=0;e<h.length;e++){(0,h[e])()}};window.addEventListener("visibilitychange",b,!1),window.addEventListener("focus",b,!1),p=!0}var v=function(e){return h.push(e),function(){var t=h.indexOf(e);h.splice(t,1)}},y=[];var g=!1;if("undefined"!=typeof window&&window.addEventListener&&!g){window.addEventListener("visibilitychange",(function(){if(f())for(var e=0;e<y.length;e++){(0,y[e])()}}),!1),g=!0}var m=function(e){return y.push(e),function(){var t=y.indexOf(e);y.splice(t,1)}};function O(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function j(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?O(Object(n),!0).forEach((function(t){w(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):O(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function w(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var S="AHOOKS_USE_REQUEST_DEFAULT_KEY",P=function(){function e(e,t,n,r){var i,o,c;this.config=void 0,this.service=void 0,this.count=0,this.unmountedFlag=!1,this.pollingWhenVisibleFlag=!1,this.pollingTimer=void 0,this.loadingDelayTimer=void 0,this.subscribe=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.debounceRun=void 0,this.throttleRun=void 0,this.limitRefresh=void 0,this.service=e,this.config=t,this.subscribe=n,r&&(this.state=j({},this.state,{},r)),this.debounceRun=this.config.debounceInterval?u()(this._run,this.config.debounceInterval):void 0,this.throttleRun=this.config.throttleInterval?a()(this._run,this.config.throttleInterval):void 0,this.limitRefresh=(i=this.refresh.bind(this),o=this.config.focusTimespan,c=!1,function(){c||(c=!0,i.apply(void 0,arguments),setTimeout((function(){c=!1}),o))}),this.config.pollingInterval&&this.unsubscribe.push(m(this.rePolling.bind(this))),this.config.refreshOnWindowFocus&&this.unsubscribe.push(v(this.limitRefresh.bind(this)))}var t=e.prototype;return t.setState=function(e){void 0===e&&(e={}),this.state=j({},this.state,{},e),this.subscribe(this.state)},t._run=function(){for(var e=this,t=arguments.length,n=new Array(t),r=0;r<t;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(){e.setState({loading:!0})}),this.config.loadingDelay)),this.service.apply(this,n).then((function(t){if(!e.unmountedFlag&&i===e.count){e.loadingDelayTimer&&clearTimeout(e.loadingDelayTimer);var r=e.config.formatResult?e.config.formatResult(t):t;return e.setState({data:r,error:void 0,loading:!1}),e.config.onSuccess&&e.config.onSuccess(r,n),r}})).catch((function(t){if(!e.unmountedFlag&&i===e.count)return e.loadingDelayTimer&&clearTimeout(e.loadingDelayTimer),e.setState({data:void 0,error:t,loading:!1}),e.config.onError&&e.config.onError(t,n),console.error(t),t})).finally((function(){if(!e.unmountedFlag&&i===e.count&&e.config.pollingInterval){if(!f()&&!e.config.pollingWhenHidden)return void(e.pollingWhenVisibleFlag=!0);e.pollingTimer=setTimeout((function(){e._run.apply(e,n)}),e.config.pollingInterval)}}))},t.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)},t.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})},t.refresh=function(){return this.run.apply(this,this.state.params)},t.rePolling=function(){this.pollingWhenVisibleFlag&&(this.pollingWhenVisibleFlag=!1,this.refresh())},t.mutate=function(e){"function"==typeof e?this.setState({data:e(this.state.data)||{}}):this.setState({data:e})},t.unmount=function(){this.unmountedFlag=!0,this.cancel(),this.unsubscribe.forEach((function(e){e()}))},e}();var E=function(e,t){var n,i=t||{},o=i.refreshDeps,u=void 0===o?[]:o,c=i.manual,a=void 0!==c&&c,f=i.onSuccess,h=void 0===f?function(){}:f,p=i.onError,b=void 0===p?function(){}:p,v=i.defaultLoading,y=void 0!==v&&v,g=i.loadingDelay,m=i.pollingInterval,O=void 0===m?0:m,w=i.pollingWhenHidden,E=void 0===w||w,T=i.defaultParams,R=void 0===T?[]:T,D=i.refreshOnWindowFocus,x=void 0!==D&&D,k=i.focusTimespan,M=void 0===k?5e3:k,C=i.fetchKey,F=i.cacheKey,W=i.debounceInterval,I=i.throttleInterval,_=i.initialData,K=i.ready,L=void 0===K||K,N=Object(r.useRef)(S),z=l(e),q=l(h),$=l(b),U=l(C);"formatResult"in i&&(n=i.formatResult);var A={formatResult:l(n),onSuccess:q,onError:$,loadingDelay:g,pollingInterval:O,pollingWhenHidden:E,refreshOnWindowFocus:x,focusTimespan:M,debounceInterval:W,throttleInterval:I},H=l((function(e,t){Q((function(n){return n[e]=t,j({},n)}))}),[]),V=Object(r.useState)((function(){if(F){var e=null==(n=s[F])?void 0:n.data;if(e){N.current=e.newstFetchKey;var t={};return Object.keys(e.fetches).forEach((function(n){var r=e.fetches[n],i=new P(z,A,H.bind(null,n),{loading:r.loading,params:r.params,data:r.data,error:r.error});t[n]=i.state})),t}}var n;return[]})),Y=V[0],Q=V[1],B=Object(r.useRef)(Y);B.current=Y;var G=Object(r.useRef)(),J=Object(r.useCallback)((function(){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];if(L){if(U){var i=U.apply(void 0,n);N.current=void 0===i?S:i}var o=N.current,u=B.current[o];if(!u){var c=new P(z,A,H.bind(null,o),{data:_});u=c.state,Q((function(e){return e[o]=u,j({},e)}))}return(e=u).run.apply(e,n)}G.current=n}),[C,H,L]),X=Object(r.useRef)(J);X.current=J,Object(r.useEffect)((function(){F&&function(e,t){s[e]&&clearTimeout(s[e].timer);var n=setTimeout((function(){delete s[e]}),3e5);s[e]={data:t,timer:n}}(F,{fetches:Y,newstFetchKey:N.current})}),[F,Y]);var Z=Object(r.useRef)(!1);d((function(){L&&(!Z.current&&G.current&&X.current.apply(X,G.current),Z.current=!0)}),[L]),Object(r.useEffect)((function(){a||(Object.keys(Y).length>0?Object.values(Y).forEach((function(e){e.refresh()})):X.current.apply(X,R))}),[]);var ee=Object(r.useCallback)((function(){Object.values(B.current).forEach((function(e){e.unmount()})),N.current=S,Q({}),B.current={}}),[Q]);d((function(){a||Object.values(B.current).forEach((function(e){e.refresh()}))}),[].concat(u)),Object(r.useEffect)((function(){return function(){Object.values(B.current).forEach((function(e){e.unmount()}))}}),[]);var te=Object(r.useCallback)((function(e){return function(){throw new Error("Cannot call "+e+" when service not executed once.")}}),[]);return j({loading:L&&!a||y,data:_,error:void 0,params:[],cancel:te("cancel"),refresh:te("refresh"),mutate:te("mutate")},Y[N.current]||{},{run:J,fetches:Y,reset:ee})};function T(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function R(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?T(Object(n),!0).forEach((function(t){D(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):T(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function D(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var x=function(e,t){var n=t.refreshDeps,i=void 0===n?[]:n,o=t.ref,u=t.isNoMore,c=t.threshold,a=void 0===c?100:c,f=(t.fetchKey,function(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(i[n]=e[n]);return i}(t,["refreshDeps","ref","isNoMore","threshold","fetchKey"])),s=Object(r.useState)(!1),l=s[0],h=s[1];Object(r.useEffect)((function(){t.fetchKey&&console.warn("useRequest loadMore mode don't need fetchKey!")}),[]);var p=E(e,R({},f,{fetchKey:function(e){var t;return(null==e||null==(t=e.list)?void 0:t.length)||0},onSuccess:function(){h(!1),t.onSuccess&&t.onSuccess.apply(t,arguments)}})),b=p.data,v=p.run,y=p.params,g=p.reset,m=p.loading,O=p.fetches,j=Object(r.useCallback)((function(){g();var e=y.slice(1);v.apply(void 0,[void 0].concat(e))}),[v,g,y]),w=Object(r.useRef)(j);w.current=j,d((function(){t.manual||w.current()}),[].concat(i));var S=Object(r.useMemo)((function(){var e=[],t=b;return Object.values(O).forEach((function(n){var r,i;(null==(r=n.data)?void 0:r.list)&&(e=e.concat(null==(i=n.data)?void 0:i.list));n.loading||(t=n.data)})),R({},t,{list:e})}),[O,b]),P=!!u&&(!m&&!l&&u(S)),T=Object(r.useCallback)((function(){if(!P){h(!0);var e=y.slice(1);v.apply(void 0,[S].concat(e))}}),[P,v,S,y]),D=Object(r.useCallback)((function(){!m&&!l&&o&&o.current&&o.current.scrollHeight-o.current.scrollTop<=o.current.clientHeight+a&&T()}),[m,o,T]);return Object(r.useEffect)((function(){return o&&o.current?(o.current.addEventListener("scroll",D),function(){o&&o.current&&o.current.removeEventListener("scroll",D)}):function(){}}),[D]),R({},p,{data:S,reload:j,loading:m&&0===S.list.length,loadMore:T,loadingMore:l,noMore:P})};function k(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function M(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?k(Object(n),!0).forEach((function(t){C(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):k(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function C(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function F(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(i[n]=e[n]);return i}var W=function(e,t){t.paginated;var n=t.defaultPageSize,i=void 0===n?10:n,o=t.refreshDeps,u=void 0===o?[]:o,c=t.fetchKey,a=F(t,["paginated","defaultPageSize","refreshDeps","fetchKey"]);Object(r.useEffect)((function(){c&&console.error("useRequest pagination's fetchKey will not work!")}),[]);var f=E(e,M({defaultParams:[{current:1,pageSize:i}]},a)),s=f.data,l=f.params,h=f.run,p=f.loading,b=F(f,["data","params","run","loading"]),v=l&&l[0]?l[0]:{},y=v.current,g=void 0===y?1:y,m=v.pageSize,O=void 0===m?i:m,j=v.sorter,w=void 0===j?{}:j,S=v.filters,P=void 0===S?{}:S,T=Object(r.useCallback)((function(e){var t=l[0],n=l.slice(1);h.apply(void 0,[M({},t,{},e)].concat(n))}),[h,l]),R=(null==s?void 0:s.total)||0,D=Object(r.useMemo)((function(){return Math.ceil(R/O)}),[O,R]),x=Object(r.useCallback)((function(e,t){var n=e<=0?1:e,r=t<=0?1:t,i=Math.ceil(R/r);n>i&&(n=i),T({current:e,pageSize:t})}),[R,T]),k=Object(r.useCallback)((function(e){x(e,O)}),[x,O]),C=Object(r.useCallback)((function(e){x(g,e)}),[x,g]),W=Object(r.useRef)(k);W.current=k,d((function(){t.manual||W.current(1)}),[].concat(u));var I=Object(r.useCallback)((function(e,t,n){T({current:e.current,pageSize:e.pageSize||i,filters:t,sorter:n})}),[P,w,T]);return M({loading:p,data:s,params:l,run:h,pagination:{current:g,pageSize:O,total:R,totalPage:D,onChange:x,changeCurrent:k,changePageSize:C},tableProps:{dataSource:(null==s?void 0:s.list)||[],loading:p,onChange:I,pagination:{current:g,pageSize:O,total:R}},sorter:w,filters:P},b)},I=i.a.createContext({});I.displayName="UseRequestConfigContext";var _=I;function K(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(i[n]=e[n]);return i}function L(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function N(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var z=_.Provider;t.default=function(e,t){void 0===t&&(t={});var n=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?L(Object(n),!0).forEach((function(t){N(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):L(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},Object(r.useContext)(_),{},t),i=n.paginated,o=n.loadMore,u=n.requestMethod,c=Object(r.useRef)(i),a=Object(r.useRef)(o);if(c.current!==i)throw Error("You should not modify the paginated of options");if(a.current!==o)throw Error("You should not modify the loadMore of options");c.current=i,a.current=o;var f,s=function(){return fetch.apply(void 0,arguments).then((function(e){if(e.ok)return e.json();throw new Error(e.statusText)}))},l=u||s;if("string"==typeof e)f=function(){return l(e)};else if("object"==typeof e){var d=e.url,h=K(e,["url"]);f=function(){return u?u(e):s(d,h)}}else f=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return new Promise((function(t,r){var i=e.apply(void 0,n);if(i.then)i.then((function(e){return t(e)})).catch((function(e){return r(e)}));else if("string"==typeof i)l(i).then((function(e){t(e)})).catch((function(e){return r(e)}));else if("object"==typeof i)if(u)u(i).then((function(e){t(e)})).catch((function(e){return r(e)}));else{var o=i.url,c=K(i,["url"]);s(o,c).then((function(e){t(e)})).catch((function(e){return r(e)}))}}))};return o?x(f,n):i?W(f,n):E(f,n)}}])})); | ||
!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(i){if(e[i])return e[i].exports;var r=e[i]={i:i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=t,n.c=e,n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},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 i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(i,r,function(e){return t[e]}.bind(null,r));return i},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,i=/^[-+]0x[0-9a-f]+$/i,r=/^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=r.test(t);return a||o.test(t)?u(t.slice(2),a?2:8):i.test(t)?NaN:+t}t.exports=function(t,e,n){var i,r,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=i,o=r;return i=r=void 0,s=e,u=t.apply(o,n)}function m(t){return s=t,a=setTimeout(O,e),f?y(t):u}function j(t){var n=t-c;return void 0===c||n>=e||n<0||g&&t-s>=o}function O(){var t=h();if(j(t))return w(t);a=setTimeout(O,function(t){var n=e-(t-c);return g?d(n,o-(t-s)):n}(t))}function w(t){return a=void 0,b&&i?y(t):(i=r=void 0,u)}function T(){var t=h(),n=j(t);if(i=arguments,r=this,c=t,n){if(void 0===a)return m(c);if(g)return a=setTimeout(O,e),y(c)}return void 0===a&&(a=setTimeout(O,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,i=c=r=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,i=/^[-+]0x[0-9a-f]+$/i,r=/^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 i,r,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=i,o=r;return i=r=void 0,s=e,u=t.apply(o,n)}function m(t){return s=t,a=setTimeout(O,e),f?y(t):u}function j(t){var n=t-c;return void 0===c||n>=e||n<0||v&&t-s>=o}function O(){var t=h();if(j(t))return w(t);a=setTimeout(O,function(t){var n=e-(t-c);return v?d(n,o-(t-s)):n}(t))}function w(t){return a=void 0,b&&i?y(t):(i=r=void 0,u)}function T(){var t=h(),n=j(t);if(i=arguments,r=this,c=t,n){if(void 0===a)return m(c);if(v)return a=setTimeout(O,e),y(c)}return void 0===a&&(a=setTimeout(O,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,i=c=r=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=r.test(t);return a||o.test(t)?u(t.slice(2),a?2:8):i.test(t)?NaN:+t}t.exports=function(t,e,n){var i=!0,r=!0;if("function"!=typeof t)throw new TypeError("Expected a function");return p(n)&&(i="leading"in n?!!n.leading:i,r="trailing"in n?!!n.trailing:r),v(t,e,{leading:i,maxWait:e,trailing:r})}}).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 E})),n.d(e,"useLoadMore",(function(){return S})),n.d(e,"UseRequestProvider",(function(){return D}));function i(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(i=Object.getOwnPropertySymbols(t);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(t,i[r])&&(n[i[r]]=t[i[r]])}return n}var r=n(0),o=n.n(r),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,e){void 0===e&&(e=[]);var n=Object(r.useRef)((function(){throw new Error("Cannot call an event handler while rendering.")}));Object(r.useEffect)((function(){n.current=t}),[t].concat(e));var i=Object(r.useCallback)((function(){var t=n.current;if(t)return t.apply(void 0,arguments)}),[n]);if("function"==typeof t)return i},h=function(t,e){var n=Object(r.useRef)(!1);Object(r.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 j=function(t){return y.push(t),function(){var e=y.indexOf(t);y.splice(e,1)}},O="AHOOKS_USE_REQUEST_DEFAULT_KEY",w=function(){function t(t,e,n,i){var r,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,i&&(this.state=Object.assign(Object.assign({},this.state),i)),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=(r=this.refresh.bind(this),o=this.config.focusTimespan,u=!1,function(){u||(u=!0,r.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(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),i=0;i<e;i++)n[i]=arguments[i];this.pollingTimer&&clearTimeout(this.pollingTimer),this.loadingDelayTimer&&clearTimeout(this.loadingDelayTimer),this.count+=1;var r=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&&r===t.count){t.loadingDelayTimer&&clearTimeout(t.loadingDelayTimer);var i=t.config.formatResult?t.config.formatResult(e):e;return t.setState({data:i,error:void 0,loading:!1}),t.config.onSuccess&&t.config.onSuccess(i,n),i}})).catch((function(e){if(!t.unmountedFlag&&r===t.count)return t.loadingDelayTimer&&clearTimeout(t.loadingDelayTimer),t.setState({data:void 0,error:e,loading:!1}),t.config.onError&&t.config.onError(e,n),console.error(e),e})).finally((function(){if(!t.unmountedFlag&&r===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,i=e||{},o=i.refreshDeps,u=void 0===o?[]:o,a=i.manual,c=void 0!==a&&a,s=i.onSuccess,f=void 0===s?function(){}:s,v=i.onError,p=void 0===v?function(){}:v,g=i.defaultLoading,b=void 0!==g&&g,y=i.loadingDelay,m=i.pollingInterval,j=void 0===m?0:m,T=i.pollingWhenHidden,S=void 0===T||T,E=i.defaultParams,R=void 0===E?[]:E,x=i.refreshOnWindowFocus,D=void 0!==x&&x,P=i.focusTimespan,M=void 0===P?5e3:P,C=i.fetchKey,F=i.cacheKey,k=i.debounceInterval,I=i.throttleInterval,W=i.initialData,_=i.ready,K=void 0===_||_,L=Object(r.useRef)(O),N=d(t),z=d(f),q=d(p),$=d(C);"formatResult"in i&&(n=i.formatResult);var U={formatResult:d(n),onSuccess:z,onError:q,loadingDelay:y,pollingInterval:j,pollingWhenHidden:S,refreshOnWindowFocus:D,focusTimespan:M,debounceInterval:k,throttleInterval:I},A=d((function(t,e){Y((function(n){return n[t]=e,Object.assign({},n)}))}),[]),H=Object(r.useState)((function(){if(F){var t=null===(n=l[F])||void 0===n?void 0:n.data;if(t){L.current=t.newstFetchKey;var e={};return Object.keys(t.fetches).forEach((function(n){var i=t.fetches[n],r=new w(N,U,A.bind(null,n),{loading:i.loading,params:i.params,data:i.data,error:i.error});e[n]=r.state})),e}}var n;return[]})),V=H[0],Y=H[1],Q=Object(r.useRef)(V);Q.current=V;var B=Object(r.useRef)(),G=Object(r.useCallback)((function(){for(var t,e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];if(K){if($){var r=$.apply(void 0,n);L.current=void 0===r?O:r}var o=L.current,u=Q.current[o];if(!u){var a=new w(N,U,A.bind(null,o),{data:W});u=a.state,Y((function(t){return t[o]=u,Object.assign({},t)}))}return(t=u).run.apply(t,n)}B.current=n}),[C,A,K]),J=Object(r.useRef)(G);J.current=G,Object(r.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:V,newstFetchKey:L.current})}),[F,V]);var X=Object(r.useRef)(!1);h((function(){K&&(!X.current&&B.current&&J.current.apply(J,B.current),X.current=!0)}),[K]),Object(r.useEffect)((function(){c||(Object.keys(V).length>0?Object.values(V).forEach((function(t){t.refresh()})):J.current.apply(J,R))}),[]);var Z=Object(r.useCallback)((function(){Object.values(Q.current).forEach((function(t){t.unmount()})),L.current=O,Y({}),Q.current={}}),[Y]);h((function(){c||Object.values(Q.current).forEach((function(t){t.refresh()}))}),[].concat(u)),Object(r.useEffect)((function(){return function(){Object.values(Q.current).forEach((function(t){t.unmount()}))}}),[]);var tt=Object(r.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:tt("cancel"),refresh:tt("refresh"),mutate:tt("mutate")},V[L.current]||{}),{run:G,fetches:V,reset:Z})};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,i(e,["refreshDeps","ref","isNoMore","threshold","fetchKey"])),l=Object(r.useState)(!1),d=l[0],v=l[1];Object(r.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,j=p.loading,O=p.fetches,w=Object(r.useCallback)((function(){m();var t=y.slice(1);b.apply(void 0,[void 0].concat(t))}),[b,m,y]),S=Object(r.useRef)(w);S.current=w,h((function(){e.manual||S.current()}),[].concat(o));var E=Object(r.useMemo)((function(){var t=[],e=g;return Object.values(O).forEach((function(n){var i,r;(null===(i=n.data)||void 0===i?void 0:i.list)&&(t=t.concat(null===(r=n.data)||void 0===r?void 0:r.list)),n.loading||(e=n.data)})),Object.assign(Object.assign({},e),{list:t})}),[O,g]),R=!!a&&(!j&&!d&&a(E)),x=Object(r.useCallback)((function(){if(!R){v(!0);var t=y.slice(1);b.apply(void 0,[E].concat(t))}}),[R,b,E,y]),D=Object(r.useCallback)((function(){!j&&!d&&u&&u.current&&u.current.scrollHeight-u.current.scrollTop<=u.current.clientHeight+s&&x()}),[j,u,x]);return Object(r.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:E,reload:w,loading:j&&0===E.list.length,loadMore:x,loadingMore:d,noMore:R})};var E=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=i(e,["paginated","defaultPageSize","refreshDeps","fetchKey"]);Object(r.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=i(f,["data","params","run","loading"]),b=d&&d[0]?d[0]:{},y=b.current,m=void 0===y?1:y,j=b.pageSize,O=void 0===j?o:j,w=b.sorter,S=void 0===w?{}:w,E=b.filters,R=void 0===E?{}:E,x=Object(r.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]),D=(null==l?void 0:l.total)||0,P=Object(r.useMemo)((function(){return Math.ceil(D/O)}),[O,D]),M=Object(r.useCallback)((function(t,e){var n=t<=0?1:t,i=e<=0?1:e,r=Math.ceil(D/i);n>r&&(n=r),x({current:t,pageSize:e})}),[D,x]),C=Object(r.useCallback)((function(t){M(t,O)}),[M,O]),F=Object(r.useCallback)((function(t){M(m,t)}),[M,m]),k=Object(r.useRef)(C);k.current=C,h((function(){e.manual||k.current(1)}),[].concat(a));var I=Object(r.useCallback)((function(t,e,n){x({current:t.current,pageSize:t.pageSize||o,filters:e,sorter:n})}),[R,S,x]);return Object.assign({loading:p,data:l,params:d,run:v,pagination:{current:m,pageSize:O,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:O,total:D}},sorter:S,filters:R},g)},R=o.a.createContext({});R.displayName="UseRequestConfigContext";var x=R;var D=x.Provider;e.default=function(t,e){void 0===e&&(e={});var n=Object(r.useContext)(x),o=Object.assign(Object.assign({},n),e),u=o.paginated,a=o.loadMore,c=o.requestMethod,s=Object(r.useRef)(u),f=Object(r.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=i(t,["url"]);l=function(){return c?c(t):d(v,p)}}else l=function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return new Promise((function(e,r){var o=t.apply(void 0,n);if(o.then)o.then((function(t){return e(t)})).catch((function(t){return r(t)}));else if("string"==typeof o)h(o).then((function(t){e(t)})).catch((function(t){return r(t)}));else if("object"==typeof o)if(c)c(o).then((function(t){e(t)})).catch((function(t){return r(t)}));else{var u=o.url,a=i(o,["url"]);d(u,a).then((function(t){e(t)})).catch((function(t){return r(t)}))}}))};return a?S(l,o):u?E(l,o):T(l,o)}}])})); |
@@ -1,13 +0,2 @@ | ||
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } | ||
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } | ||
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
import { __rest } from "tslib"; | ||
import { useRef, useContext } from 'react'; | ||
@@ -19,8 +8,9 @@ import useAsync from './useAsync'; | ||
function useRequest(service) { | ||
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
function useRequest(service, options) { | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
var contextConfig = useContext(ConfigContext); | ||
var finalOptions = _objectSpread({}, contextConfig, {}, options); | ||
var finalOptions = Object.assign(Object.assign({}, contextConfig), options); | ||
var paginated = finalOptions.paginated, | ||
@@ -60,5 +50,5 @@ loadMore = finalOptions.loadMore, | ||
}; | ||
} else if (_typeof(service) === 'object') { | ||
} else if (typeof service === 'object') { | ||
var url = service.url, | ||
rest = _objectWithoutProperties(service, ["url"]); | ||
rest = __rest(service, ["url"]); | ||
@@ -80,3 +70,3 @@ promiseService = function promiseService() { | ||
return resolve(data); | ||
}).catch(function (e) { | ||
})["catch"](function (e) { | ||
return reject(e); | ||
@@ -87,6 +77,6 @@ }); | ||
resolve(data); | ||
}).catch(function (e) { | ||
})["catch"](function (e) { | ||
return reject(e); | ||
}); | ||
} else if (_typeof(result) === 'object') { | ||
} else if (typeof result === 'object') { | ||
// fetch 需要拆分下字段 | ||
@@ -96,3 +86,3 @@ if (requestMethod) { | ||
resolve(data); | ||
}).catch(function (e) { | ||
})["catch"](function (e) { | ||
return reject(e); | ||
@@ -102,7 +92,7 @@ }); | ||
var _url = result.url, | ||
_rest = _objectWithoutProperties(result, ["url"]); | ||
_rest = __rest(result, ["url"]); | ||
fetchProxy(_url, _rest).then(function (data) { | ||
resolve(data); | ||
}).catch(function (e) { | ||
})["catch"](function (e) { | ||
return reject(e); | ||
@@ -109,0 +99,0 @@ }); |
@@ -1,29 +0,1 @@ | ||
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } | ||
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } | ||
function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } | ||
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } | ||
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } | ||
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } | ||
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } | ||
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } | ||
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } | ||
import debounce from 'lodash.debounce'; | ||
@@ -42,16 +14,11 @@ import throttle from 'lodash.throttle'; | ||
var Fetch = /*#__PURE__*/function () { | ||
// 请求时序 | ||
// 是否卸载 | ||
// visible 后,是否继续轮询 | ||
function Fetch(service, config, subscribe, initState) { | ||
_classCallCheck(this, Fetch); | ||
// 请求时序 | ||
this.count = 0; // 是否卸载 | ||
this.config = void 0; | ||
this.service = void 0; | ||
this.count = 0; | ||
this.unmountedFlag = false; | ||
this.unmountedFlag = false; // visible 后,是否继续轮询 | ||
this.pollingWhenVisibleFlag = false; | ||
this.pollingTimer = undefined; | ||
this.loadingDelayTimer = undefined; | ||
this.subscribe = void 0; | ||
this.unsubscribe = []; | ||
@@ -70,5 +37,2 @@ this.that = this; | ||
}; | ||
this.debounceRun = void 0; | ||
this.throttleRun = void 0; | ||
this.limitRefresh = void 0; | ||
this.service = service; | ||
@@ -79,3 +43,3 @@ this.config = config; | ||
if (initState) { | ||
this.state = _objectSpread({}, this.state, {}, initState); | ||
this.state = Object.assign(Object.assign({}, this.state), initState); | ||
} | ||
@@ -96,178 +60,173 @@ | ||
_createClass(Fetch, [{ | ||
key: "setState", | ||
value: function setState() { | ||
var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
this.state = _objectSpread({}, this.state, {}, s); | ||
this.subscribe(this.state); | ||
var _proto = Fetch.prototype; | ||
_proto.setState = function setState(s) { | ||
if (s === void 0) { | ||
s = {}; | ||
} | ||
}, { | ||
key: "_run", | ||
value: function _run() { | ||
var _this = this; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
this.state = Object.assign(Object.assign({}, this.state), s); | ||
this.subscribe(this.state); | ||
}; | ||
// 取消已有定时器 | ||
if (this.pollingTimer) { | ||
clearTimeout(this.pollingTimer); | ||
} // 取消 loadingDelayTimer | ||
_proto._run = function _run() { | ||
var _this = this; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
if (this.loadingDelayTimer) { | ||
clearTimeout(this.loadingDelayTimer); | ||
} | ||
// 取消已有定时器 | ||
if (this.pollingTimer) { | ||
clearTimeout(this.pollingTimer); | ||
} // 取消 loadingDelayTimer | ||
this.count += 1; // 闭包存储当次请求的 count | ||
var currentCount = this.count; | ||
this.setState({ | ||
loading: !this.config.loadingDelay, | ||
params: args | ||
}); | ||
if (this.loadingDelayTimer) { | ||
clearTimeout(this.loadingDelayTimer); | ||
} | ||
if (this.config.loadingDelay) { | ||
this.loadingDelayTimer = setTimeout(function () { | ||
_this.setState({ | ||
loading: true | ||
}); | ||
}, this.config.loadingDelay); | ||
} | ||
this.count += 1; // 闭包存储当次请求的 count | ||
return this.service.apply(this, args).then(function (res) { | ||
if (!_this.unmountedFlag && currentCount === _this.count) { | ||
if (_this.loadingDelayTimer) { | ||
clearTimeout(_this.loadingDelayTimer); | ||
} | ||
var currentCount = this.count; | ||
this.setState({ | ||
loading: !this.config.loadingDelay, | ||
params: args | ||
}); | ||
var formattedResult = _this.config.formatResult ? _this.config.formatResult(res) : res; | ||
if (this.config.loadingDelay) { | ||
this.loadingDelayTimer = setTimeout(function () { | ||
_this.setState({ | ||
loading: true | ||
}); | ||
}, this.config.loadingDelay); | ||
} | ||
_this.setState({ | ||
data: formattedResult, | ||
error: undefined, | ||
loading: false | ||
}); | ||
return this.service.apply(this, args).then(function (res) { | ||
if (!_this.unmountedFlag && currentCount === _this.count) { | ||
if (_this.loadingDelayTimer) { | ||
clearTimeout(_this.loadingDelayTimer); | ||
} | ||
if (_this.config.onSuccess) { | ||
_this.config.onSuccess(formattedResult, args); | ||
} | ||
var formattedResult = _this.config.formatResult ? _this.config.formatResult(res) : res; | ||
return formattedResult; | ||
_this.setState({ | ||
data: formattedResult, | ||
error: undefined, | ||
loading: false | ||
}); | ||
if (_this.config.onSuccess) { | ||
_this.config.onSuccess(formattedResult, args); | ||
} | ||
}).catch(function (error) { | ||
if (!_this.unmountedFlag && currentCount === _this.count) { | ||
if (_this.loadingDelayTimer) { | ||
clearTimeout(_this.loadingDelayTimer); | ||
} | ||
_this.setState({ | ||
data: undefined, | ||
error: error, | ||
loading: false | ||
}); | ||
return formattedResult; | ||
} | ||
})["catch"](function (error) { | ||
if (!_this.unmountedFlag && currentCount === _this.count) { | ||
if (_this.loadingDelayTimer) { | ||
clearTimeout(_this.loadingDelayTimer); | ||
} | ||
if (_this.config.onError) { | ||
_this.config.onError(error, args); | ||
} | ||
_this.setState({ | ||
data: undefined, | ||
error: error, | ||
loading: false | ||
}); | ||
console.error(error); | ||
return error; // throw error; | ||
if (_this.config.onError) { | ||
_this.config.onError(error, args); | ||
} | ||
}).finally(function () { | ||
if (!_this.unmountedFlag && currentCount === _this.count) { | ||
if (_this.config.pollingInterval) { | ||
// 如果屏幕隐藏,并且 !pollingWhenHidden, 则停止轮询,并记录 flag,等 visible 时,继续轮询 | ||
if (!isDocumentVisible() && !_this.config.pollingWhenHidden) { | ||
_this.pollingWhenVisibleFlag = true; | ||
return; | ||
} | ||
_this.pollingTimer = setTimeout(function () { | ||
_this._run.apply(_this, args); | ||
}, _this.config.pollingInterval); | ||
console.error(error); | ||
return error; // throw error; | ||
} | ||
})["finally"](function () { | ||
if (!_this.unmountedFlag && currentCount === _this.count) { | ||
if (_this.config.pollingInterval) { | ||
// 如果屏幕隐藏,并且 !pollingWhenHidden, 则停止轮询,并记录 flag,等 visible 时,继续轮询 | ||
if (!isDocumentVisible() && !_this.config.pollingWhenHidden) { | ||
_this.pollingWhenVisibleFlag = true; | ||
return; | ||
} | ||
_this.pollingTimer = setTimeout(function () { | ||
_this._run.apply(_this, args); | ||
}, _this.config.pollingInterval); | ||
} | ||
}); | ||
} | ||
}, { | ||
key: "run", | ||
value: function run() { | ||
if (this.debounceRun) { | ||
this.debounceRun.apply(this, arguments); // TODO 如果 options 存在 debounceInterval,或 throttleInterval,则 run 和 refresh 不会返回 Promise。 带类型需要修复后,此处变成 return;。 | ||
return Promise.resolve(null); | ||
} | ||
}); | ||
}; | ||
if (this.throttleRun) { | ||
this.throttleRun.apply(this, arguments); | ||
return Promise.resolve(null); | ||
} | ||
_proto.run = function run() { | ||
if (this.debounceRun) { | ||
this.debounceRun.apply(this, arguments); // TODO 如果 options 存在 debounceInterval,或 throttleInterval,则 run 和 refresh 不会返回 Promise。 带类型需要修复后,此处变成 return;。 | ||
return this._run.apply(this, arguments); | ||
return Promise.resolve(null); | ||
} | ||
}, { | ||
key: "cancel", | ||
value: function cancel() { | ||
if (this.debounceRun) { | ||
this.debounceRun.cancel(); | ||
} | ||
if (this.throttleRun) { | ||
this.throttleRun.cancel(); | ||
} | ||
if (this.throttleRun) { | ||
this.throttleRun.apply(this, arguments); | ||
return Promise.resolve(null); | ||
} | ||
if (this.loadingDelayTimer) { | ||
clearTimeout(this.loadingDelayTimer); | ||
} | ||
return this._run.apply(this, arguments); | ||
}; | ||
if (this.pollingTimer) { | ||
clearTimeout(this.pollingTimer); | ||
} | ||
_proto.cancel = function cancel() { | ||
if (this.debounceRun) { | ||
this.debounceRun.cancel(); | ||
} | ||
this.pollingWhenVisibleFlag = false; | ||
this.count += 1; | ||
this.setState({ | ||
loading: false | ||
}); | ||
if (this.throttleRun) { | ||
this.throttleRun.cancel(); | ||
} | ||
}, { | ||
key: "refresh", | ||
value: function refresh() { | ||
return this.run.apply(this, _toConsumableArray(this.state.params)); | ||
if (this.loadingDelayTimer) { | ||
clearTimeout(this.loadingDelayTimer); | ||
} | ||
}, { | ||
key: "rePolling", | ||
value: function rePolling() { | ||
if (this.pollingWhenVisibleFlag) { | ||
this.pollingWhenVisibleFlag = false; | ||
this.refresh(); | ||
} | ||
if (this.pollingTimer) { | ||
clearTimeout(this.pollingTimer); | ||
} | ||
}, { | ||
key: "mutate", | ||
value: function mutate(data) { | ||
if (typeof data === 'function') { | ||
this.setState({ | ||
// eslint-disable-next-line react/no-access-state-in-setstate | ||
data: data(this.state.data) || {} | ||
}); | ||
} else { | ||
this.setState({ | ||
data: data | ||
}); | ||
} | ||
this.pollingWhenVisibleFlag = false; | ||
this.count += 1; | ||
this.setState({ | ||
loading: false | ||
}); | ||
}; | ||
_proto.refresh = function refresh() { | ||
return this.run.apply(this, this.state.params); | ||
}; | ||
_proto.rePolling = function rePolling() { | ||
if (this.pollingWhenVisibleFlag) { | ||
this.pollingWhenVisibleFlag = false; | ||
this.refresh(); | ||
} | ||
}, { | ||
key: "unmount", | ||
value: function unmount() { | ||
this.unmountedFlag = true; | ||
this.cancel(); | ||
this.unsubscribe.forEach(function (s) { | ||
s(); | ||
}; | ||
_proto.mutate = function mutate(data) { | ||
if (typeof data === 'function') { | ||
this.setState({ | ||
// eslint-disable-next-line react/no-access-state-in-setstate | ||
data: data(this.state.data) || {} | ||
}); | ||
} else { | ||
this.setState({ | ||
data: data | ||
}); | ||
} | ||
}]); | ||
}; | ||
_proto.unmount = function unmount() { | ||
this.unmountedFlag = true; | ||
this.cancel(); | ||
this.unsubscribe.forEach(function (s) { | ||
s(); | ||
}); | ||
}; | ||
return Fetch; | ||
@@ -337,3 +296,3 @@ }(); | ||
s[key] = data; | ||
return _objectSpread({}, s); | ||
return Object.assign({}, s); | ||
}); | ||
@@ -368,5 +327,4 @@ }, []); | ||
}), | ||
_useState2 = _slicedToArray(_useState, 2), | ||
fetches = _useState2[0], | ||
setFeches = _useState2[1]; | ||
fetches = _useState[0], | ||
setFeches = _useState[1]; | ||
@@ -407,3 +365,3 @@ var fetchesRef = useRef(fetches); | ||
s[currentFetchKey] = currentFetch; | ||
return _objectSpread({}, s); | ||
return Object.assign({}, s); | ||
}); | ||
@@ -430,3 +388,3 @@ } | ||
if (!hasTriggeredByReady.current && readyMemoryParams.current) { | ||
runRef.current.apply(runRef, _toConsumableArray(readyMemoryParams.current)); | ||
runRef.current.apply(runRef, readyMemoryParams.current); | ||
} | ||
@@ -448,3 +406,3 @@ | ||
// 第一次默认执行,可以通过 defaultParams 设置参数 | ||
runRef.current.apply(runRef, _toConsumableArray(defaultParams)); | ||
runRef.current.apply(runRef, defaultParams); | ||
} | ||
@@ -471,3 +429,3 @@ } | ||
} | ||
}, _toConsumableArray(refreshDeps)); // 卸载组件触发 | ||
}, [].concat(refreshDeps)); // 卸载组件触发 | ||
@@ -483,6 +441,6 @@ useEffect(function () { | ||
return function () { | ||
throw new Error("Cannot call ".concat(name, " when service not executed once.")); | ||
throw new Error("Cannot call " + name + " when service not executed once."); | ||
}; | ||
}, []); | ||
return _objectSpread({ | ||
return Object.assign(Object.assign({ | ||
loading: ready && !manual || defaultLoading, | ||
@@ -495,3 +453,3 @@ data: initialData, | ||
mutate: notExecutedWarning('mutate') | ||
}, fetches[newstFetchKey.current] || {}, { | ||
}, fetches[newstFetchKey.current] || {}), { | ||
run: run, | ||
@@ -498,0 +456,0 @@ fetches: fetches, |
@@ -1,29 +0,2 @@ | ||
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } | ||
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } | ||
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } | ||
function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } | ||
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } | ||
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } | ||
function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } | ||
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } | ||
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } | ||
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } | ||
import { __rest } from "tslib"; | ||
import { useRef, useCallback, useMemo, useEffect, useState } from 'react'; | ||
@@ -41,8 +14,7 @@ import useAsync from './useAsync'; | ||
fetchKey = options.fetchKey, | ||
restOptions = _objectWithoutProperties(options, ["refreshDeps", "ref", "isNoMore", "threshold", "fetchKey"]); | ||
restOptions = __rest(options, ["refreshDeps", "ref", "isNoMore", "threshold", "fetchKey"]); | ||
var _useState = useState(false), | ||
_useState2 = _slicedToArray(_useState, 2), | ||
loadingMore = _useState2[0], | ||
setLoadingMore = _useState2[1]; | ||
loadingMore = _useState[0], | ||
setLoadingMore = _useState[1]; | ||
@@ -54,7 +26,7 @@ useEffect(function () { | ||
}, []); | ||
var result = useAsync(service, _objectSpread({}, restOptions, { | ||
var result = useAsync(service, Object.assign(Object.assign({}, restOptions), { | ||
fetchKey: function fetchKey(d) { | ||
var _d$list; | ||
var _a; | ||
return (d === null || d === void 0 ? void 0 : (_d$list = d.list) === null || _d$list === void 0 ? void 0 : _d$list.length) || 0; | ||
return ((_a = d === null || d === void 0 ? void 0 : d.list) === null || _a === void 0 ? void 0 : _a.length) || 0; | ||
}, | ||
@@ -77,7 +49,4 @@ onSuccess: function onSuccess() { | ||
reset(); | ||
var _params = _toArray(params), | ||
restParams = _params.slice(1); | ||
run.apply(void 0, [undefined].concat(_toConsumableArray(restParams))); | ||
var restParams = params.slice(1); | ||
run.apply(void 0, [undefined].concat(restParams)); | ||
}, [run, reset, params]); | ||
@@ -93,3 +62,3 @@ var reloadRef = useRef(reload); | ||
} | ||
}, _toConsumableArray(refreshDeps)); | ||
}, [].concat(refreshDeps)); | ||
var dataGroup = useMemo(function () { | ||
@@ -100,8 +69,6 @@ var listGroup = []; // 在 loadMore 时,不希望清空上一次的 data。需要把最后一个 非 loading 的请求 data,放回去。 | ||
Object.values(fetches).forEach(function (h) { | ||
var _h$data; | ||
var _a, _b; | ||
if ((_h$data = h.data) === null || _h$data === void 0 ? void 0 : _h$data.list) { | ||
var _h$data2; | ||
listGroup = listGroup.concat((_h$data2 = h.data) === null || _h$data2 === void 0 ? void 0 : _h$data2.list); | ||
if ((_a = h.data) === null || _a === void 0 ? void 0 : _a.list) { | ||
listGroup = listGroup.concat((_b = h.data) === null || _b === void 0 ? void 0 : _b.list); | ||
} | ||
@@ -113,3 +80,3 @@ | ||
}); | ||
return _objectSpread({}, lastNoLoadingData, { | ||
return Object.assign(Object.assign({}, lastNoLoadingData), { | ||
list: listGroup | ||
@@ -125,7 +92,4 @@ }); | ||
setLoadingMore(true); | ||
var _params2 = _toArray(params), | ||
restParams = _params2.slice(1); | ||
run.apply(void 0, [dataGroup].concat(_toConsumableArray(restParams))); | ||
var restParams = params.slice(1); | ||
run.apply(void 0, [dataGroup].concat(restParams)); | ||
}, [noMore, run, dataGroup, params]); | ||
@@ -157,3 +121,3 @@ /* 上拉加载的方法 */ | ||
}, [scrollMethod]); | ||
return _objectSpread({}, result, { | ||
return Object.assign(Object.assign({}, result), { | ||
data: dataGroup, | ||
@@ -160,0 +124,0 @@ reload: reload, |
@@ -1,25 +0,2 @@ | ||
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } | ||
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } | ||
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } | ||
function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } | ||
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } | ||
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } | ||
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } | ||
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } | ||
import { __rest } from "tslib"; | ||
import { useCallback, useEffect, useMemo, useRef } from 'react'; | ||
@@ -36,3 +13,3 @@ import useAsync from './useAsync'; | ||
fetchKey = options.fetchKey, | ||
restOptions = _objectWithoutProperties(options, ["paginated", "defaultPageSize", "refreshDeps", "fetchKey"]); | ||
restOptions = __rest(options, ["paginated", "defaultPageSize", "refreshDeps", "fetchKey"]); | ||
@@ -45,3 +22,3 @@ useEffect(function () { | ||
var _useAsync = useAsync(service, _objectSpread({ | ||
var _a = useAsync(service, Object.assign({ | ||
defaultParams: [{ | ||
@@ -52,7 +29,7 @@ current: 1, | ||
}, restOptions)), | ||
data = _useAsync.data, | ||
params = _useAsync.params, | ||
run = _useAsync.run, | ||
loading = _useAsync.loading, | ||
rest = _objectWithoutProperties(_useAsync, ["data", "params", "run", "loading"]); | ||
data = _a.data, | ||
params = _a.params, | ||
run = _a.run, | ||
loading = _a.loading, | ||
rest = __rest(_a, ["data", "params", "run", "loading"]); | ||
@@ -71,7 +48,5 @@ var _ref = params && params[0] ? params[0] : {}, | ||
var runChangePaination = useCallback(function (paginationParams) { | ||
var _params = _toArray(params), | ||
oldPaginationParams = _params[0], | ||
restParams = _params.slice(1); | ||
run.apply(void 0, [_objectSpread({}, oldPaginationParams, {}, paginationParams)].concat(_toConsumableArray(restParams))); | ||
var oldPaginationParams = params[0], | ||
restParams = params.slice(1); | ||
run.apply(void 0, [Object.assign(Object.assign({}, oldPaginationParams), paginationParams)].concat(restParams)); | ||
}, [run, params]); | ||
@@ -111,3 +86,3 @@ var total = (data === null || data === void 0 ? void 0 : data.total) || 0; | ||
} | ||
}, _toConsumableArray(refreshDeps)); // 表格翻页 排序 筛选等 | ||
}, [].concat(refreshDeps)); // 表格翻页 排序 筛选等 | ||
@@ -122,3 +97,3 @@ var changeTable = useCallback(function (p, f, s) { | ||
}, [filters, sorter, runChangePaination]); | ||
return _objectSpread({ | ||
return Object.assign({ | ||
loading: loading, | ||
@@ -125,0 +100,0 @@ data: data, |
@@ -1,7 +0,2 @@ | ||
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } | ||
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } | ||
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } | ||
import { __rest } from "tslib"; | ||
import request from 'umi-request'; | ||
@@ -17,5 +12,5 @@ import useAsync from './useAsync'; | ||
}; | ||
} else if (_typeof(service) === 'object') { | ||
} else if (typeof service === 'object') { | ||
var url = service.url, | ||
rest = _objectWithoutProperties(service, ["url"]); | ||
rest = __rest(service, ["url"]); | ||
@@ -38,5 +33,5 @@ promiseService = function promiseService() { | ||
}); | ||
} else if (_typeof(result) === 'object') { | ||
} else if (typeof result === 'object') { | ||
var _url = result.url, | ||
_rest = _objectWithoutProperties(result, ["url"]); | ||
_rest = __rest(result, ["url"]); | ||
@@ -43,0 +38,0 @@ request(_url, _rest).then(function (data) { |
@@ -19,7 +19,7 @@ var cache = {}; | ||
var getCache = function getCache(key) { | ||
var _cache$key; | ||
var _a; | ||
return (_cache$key = cache[key]) === null || _cache$key === void 0 ? void 0 : _cache$key.data; | ||
return (_a = cache[key]) === null || _a === void 0 ? void 0 : _a.data; | ||
}; | ||
export { getCache, setCache }; |
@@ -1,2 +0,2 @@ | ||
declare function usePersistFn(fn: any, dependencies?: any): ((...args: any[]) => any) | undefined; | ||
declare function usePersistFn(fn: any, dependencies?: any): (...args: any[]) => any; | ||
export default usePersistFn; |
@@ -1,13 +0,8 @@ | ||
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } | ||
import { useCallback, useRef, useEffect } from 'react'; | ||
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } | ||
function usePersistFn(fn, dependencies) { | ||
if (dependencies === void 0) { | ||
dependencies = []; | ||
} | ||
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } | ||
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } | ||
import { useCallback, useRef, useEffect } from 'react'; | ||
function usePersistFn(fn) { | ||
var dependencies = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; | ||
var ref = useRef(function () { | ||
@@ -18,3 +13,3 @@ throw new Error('Cannot call an event handler while rendering.'); | ||
ref.current = fn; | ||
}, [fn].concat(_toConsumableArray(dependencies))); | ||
}, [fn].concat(dependencies)); | ||
var persist = useCallback(function () { | ||
@@ -21,0 +16,0 @@ var refFn = ref.current; |
@@ -1,1 +0,5 @@ | ||
"use strict"; | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); |
@@ -6,12 +6,9 @@ "use strict"; | ||
}); | ||
exports.default = void 0; | ||
var _react = _interopRequireDefault(require("react")); | ||
var tslib_1 = require("tslib"); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var react_1 = tslib_1.__importDefault(require("react")); | ||
var ConfigContext = _react.default.createContext({}); | ||
var ConfigContext = react_1["default"].createContext({}); | ||
ConfigContext.displayName = 'UseRequestConfigContext'; | ||
var _default = ConfigContext; | ||
exports.default = _default; | ||
exports["default"] = ConfigContext; |
@@ -6,57 +6,34 @@ "use strict"; | ||
}); | ||
Object.defineProperty(exports, "useAsync", { | ||
enumerable: true, | ||
get: function get() { | ||
return _useAsync.default; | ||
} | ||
}); | ||
Object.defineProperty(exports, "useLoadMore", { | ||
enumerable: true, | ||
get: function get() { | ||
return _useLoadMore.default; | ||
} | ||
}); | ||
Object.defineProperty(exports, "usePaginated", { | ||
enumerable: true, | ||
get: function get() { | ||
return _usePaginated.default; | ||
} | ||
}); | ||
exports.default = exports.UseRequestProvider = void 0; | ||
exports.UseRequestProvider = exports.useLoadMore = exports.usePaginated = exports.useAsync = void 0; | ||
var _react = require("react"); | ||
var tslib_1 = require("tslib"); | ||
var _useAsync = _interopRequireDefault(require("./useAsync")); | ||
var react_1 = require("react"); | ||
var _useLoadMore = _interopRequireDefault(require("./useLoadMore")); | ||
var useAsync_1 = tslib_1.__importDefault(require("./useAsync")); | ||
var _usePaginated = _interopRequireDefault(require("./usePaginated")); | ||
exports.useAsync = useAsync_1["default"]; | ||
var _configContext = _interopRequireDefault(require("./configContext")); | ||
var useLoadMore_1 = tslib_1.__importDefault(require("./useLoadMore")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
exports.useLoadMore = useLoadMore_1["default"]; | ||
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } | ||
var usePaginated_1 = tslib_1.__importDefault(require("./usePaginated")); | ||
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } | ||
exports.usePaginated = usePaginated_1["default"]; | ||
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } | ||
var configContext_1 = tslib_1.__importDefault(require("./configContext")); | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } | ||
function useRequest(service, options) { | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function useRequest(service) { | ||
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var contextConfig = (0, _react.useContext)(_configContext.default); | ||
var finalOptions = _objectSpread({}, contextConfig, {}, options); | ||
var contextConfig = react_1.useContext(configContext_1["default"]); | ||
var finalOptions = Object.assign(Object.assign({}, contextConfig), options); | ||
var paginated = finalOptions.paginated, | ||
loadMore = finalOptions.loadMore, | ||
requestMethod = finalOptions.requestMethod; | ||
var paginatedRef = (0, _react.useRef)(paginated); | ||
var loadMoreRef = (0, _react.useRef)(loadMore); | ||
var paginatedRef = react_1.useRef(paginated); | ||
var loadMoreRef = react_1.useRef(loadMore); | ||
@@ -91,5 +68,5 @@ if (paginatedRef.current !== paginated) { | ||
}; | ||
} else if (_typeof(service) === 'object') { | ||
} else if (typeof service === 'object') { | ||
var url = service.url, | ||
rest = _objectWithoutProperties(service, ["url"]); | ||
rest = tslib_1.__rest(service, ["url"]); | ||
@@ -111,3 +88,3 @@ promiseService = function promiseService() { | ||
return resolve(data); | ||
}).catch(function (e) { | ||
})["catch"](function (e) { | ||
return reject(e); | ||
@@ -118,6 +95,6 @@ }); | ||
resolve(data); | ||
}).catch(function (e) { | ||
})["catch"](function (e) { | ||
return reject(e); | ||
}); | ||
} else if (_typeof(result) === 'object') { | ||
} else if (typeof result === 'object') { | ||
// fetch 需要拆分下字段 | ||
@@ -127,3 +104,3 @@ if (requestMethod) { | ||
resolve(data); | ||
}).catch(function (e) { | ||
})["catch"](function (e) { | ||
return reject(e); | ||
@@ -133,7 +110,7 @@ }); | ||
var _url = result.url, | ||
_rest = _objectWithoutProperties(result, ["url"]); | ||
_rest = tslib_1.__rest(result, ["url"]); | ||
fetchProxy(_url, _rest).then(function (data) { | ||
resolve(data); | ||
}).catch(function (e) { | ||
})["catch"](function (e) { | ||
return reject(e); | ||
@@ -148,15 +125,14 @@ }); | ||
if (loadMore) { | ||
return (0, _useLoadMore.default)(promiseService, finalOptions); | ||
return useLoadMore_1["default"](promiseService, finalOptions); | ||
} | ||
if (paginated) { | ||
return (0, _usePaginated.default)(promiseService, finalOptions); | ||
return usePaginated_1["default"](promiseService, finalOptions); | ||
} | ||
return (0, _useAsync.default)(promiseService, finalOptions); | ||
return useAsync_1["default"](promiseService, finalOptions); | ||
} | ||
var UseRequestProvider = _configContext.default.Provider; | ||
var UseRequestProvider = configContext_1["default"].Provider; | ||
exports.UseRequestProvider = UseRequestProvider; | ||
var _default = useRequest; | ||
exports.default = _default; | ||
exports["default"] = useRequest; |
@@ -1,1 +0,5 @@ | ||
"use strict"; | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); |
@@ -6,71 +6,37 @@ "use strict"; | ||
}); | ||
exports.default = void 0; | ||
var _lodash = _interopRequireDefault(require("lodash.debounce")); | ||
var tslib_1 = require("tslib"); | ||
var _lodash2 = _interopRequireDefault(require("lodash.throttle")); | ||
var lodash_debounce_1 = tslib_1.__importDefault(require("lodash.debounce")); | ||
var _react = require("react"); | ||
var lodash_throttle_1 = tslib_1.__importDefault(require("lodash.throttle")); | ||
var _utils = require("./utils"); | ||
var react_1 = require("react"); | ||
var _cache = require("./utils/cache"); | ||
var utils_1 = require("./utils"); | ||
var _limit = _interopRequireDefault(require("./utils/limit")); | ||
var cache_1 = require("./utils/cache"); | ||
var _usePersistFn = _interopRequireDefault(require("./utils/usePersistFn")); | ||
var limit_1 = tslib_1.__importDefault(require("./utils/limit")); | ||
var _useUpdateEffect = _interopRequireDefault(require("./utils/useUpdateEffect")); | ||
var usePersistFn_1 = tslib_1.__importDefault(require("./utils/usePersistFn")); | ||
var _windowFocus = _interopRequireDefault(require("./utils/windowFocus")); | ||
var useUpdateEffect_1 = tslib_1.__importDefault(require("./utils/useUpdateEffect")); | ||
var _windowVisible = _interopRequireDefault(require("./utils/windowVisible")); | ||
var windowFocus_1 = tslib_1.__importDefault(require("./utils/windowFocus")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var windowVisible_1 = tslib_1.__importDefault(require("./utils/windowVisible")); | ||
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } | ||
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } | ||
function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } | ||
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } | ||
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } | ||
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } | ||
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } | ||
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } | ||
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } | ||
var DEFAULT_KEY = 'AHOOKS_USE_REQUEST_DEFAULT_KEY'; | ||
var Fetch = /*#__PURE__*/function () { | ||
// 请求时序 | ||
// 是否卸载 | ||
// visible 后,是否继续轮询 | ||
function Fetch(service, config, subscribe, initState) { | ||
_classCallCheck(this, Fetch); | ||
// 请求时序 | ||
this.count = 0; // 是否卸载 | ||
this.config = void 0; | ||
this.service = void 0; | ||
this.count = 0; | ||
this.unmountedFlag = false; | ||
this.unmountedFlag = false; // visible 后,是否继续轮询 | ||
this.pollingWhenVisibleFlag = false; | ||
this.pollingTimer = undefined; | ||
this.loadingDelayTimer = undefined; | ||
this.subscribe = void 0; | ||
this.unsubscribe = []; | ||
@@ -89,5 +55,2 @@ this.that = this; | ||
}; | ||
this.debounceRun = void 0; | ||
this.throttleRun = void 0; | ||
this.limitRefresh = void 0; | ||
this.service = service; | ||
@@ -98,194 +61,189 @@ this.config = config; | ||
if (initState) { | ||
this.state = _objectSpread({}, this.state, {}, initState); | ||
this.state = Object.assign(Object.assign({}, this.state), initState); | ||
} | ||
this.debounceRun = this.config.debounceInterval ? (0, _lodash.default)(this._run, this.config.debounceInterval) : undefined; | ||
this.throttleRun = this.config.throttleInterval ? (0, _lodash2.default)(this._run, this.config.throttleInterval) : undefined; | ||
this.limitRefresh = (0, _limit.default)(this.refresh.bind(this), this.config.focusTimespan); | ||
this.debounceRun = this.config.debounceInterval ? lodash_debounce_1["default"](this._run, this.config.debounceInterval) : undefined; | ||
this.throttleRun = this.config.throttleInterval ? lodash_throttle_1["default"](this._run, this.config.throttleInterval) : undefined; | ||
this.limitRefresh = limit_1["default"](this.refresh.bind(this), this.config.focusTimespan); | ||
if (this.config.pollingInterval) { | ||
this.unsubscribe.push((0, _windowVisible.default)(this.rePolling.bind(this))); | ||
this.unsubscribe.push(windowVisible_1["default"](this.rePolling.bind(this))); | ||
} | ||
if (this.config.refreshOnWindowFocus) { | ||
this.unsubscribe.push((0, _windowFocus.default)(this.limitRefresh.bind(this))); | ||
this.unsubscribe.push(windowFocus_1["default"](this.limitRefresh.bind(this))); | ||
} | ||
} | ||
_createClass(Fetch, [{ | ||
key: "setState", | ||
value: function setState() { | ||
var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
this.state = _objectSpread({}, this.state, {}, s); | ||
this.subscribe(this.state); | ||
var _proto = Fetch.prototype; | ||
_proto.setState = function setState(s) { | ||
if (s === void 0) { | ||
s = {}; | ||
} | ||
}, { | ||
key: "_run", | ||
value: function _run() { | ||
var _this = this; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
this.state = Object.assign(Object.assign({}, this.state), s); | ||
this.subscribe(this.state); | ||
}; | ||
// 取消已有定时器 | ||
if (this.pollingTimer) { | ||
clearTimeout(this.pollingTimer); | ||
} // 取消 loadingDelayTimer | ||
_proto._run = function _run() { | ||
var _this = this; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
if (this.loadingDelayTimer) { | ||
clearTimeout(this.loadingDelayTimer); | ||
} | ||
// 取消已有定时器 | ||
if (this.pollingTimer) { | ||
clearTimeout(this.pollingTimer); | ||
} // 取消 loadingDelayTimer | ||
this.count += 1; // 闭包存储当次请求的 count | ||
var currentCount = this.count; | ||
this.setState({ | ||
loading: !this.config.loadingDelay, | ||
params: args | ||
}); | ||
if (this.loadingDelayTimer) { | ||
clearTimeout(this.loadingDelayTimer); | ||
} | ||
if (this.config.loadingDelay) { | ||
this.loadingDelayTimer = setTimeout(function () { | ||
_this.setState({ | ||
loading: true | ||
}); | ||
}, this.config.loadingDelay); | ||
} | ||
this.count += 1; // 闭包存储当次请求的 count | ||
return this.service.apply(this, args).then(function (res) { | ||
if (!_this.unmountedFlag && currentCount === _this.count) { | ||
if (_this.loadingDelayTimer) { | ||
clearTimeout(_this.loadingDelayTimer); | ||
} | ||
var currentCount = this.count; | ||
this.setState({ | ||
loading: !this.config.loadingDelay, | ||
params: args | ||
}); | ||
var formattedResult = _this.config.formatResult ? _this.config.formatResult(res) : res; | ||
if (this.config.loadingDelay) { | ||
this.loadingDelayTimer = setTimeout(function () { | ||
_this.setState({ | ||
loading: true | ||
}); | ||
}, this.config.loadingDelay); | ||
} | ||
_this.setState({ | ||
data: formattedResult, | ||
error: undefined, | ||
loading: false | ||
}); | ||
return this.service.apply(this, args).then(function (res) { | ||
if (!_this.unmountedFlag && currentCount === _this.count) { | ||
if (_this.loadingDelayTimer) { | ||
clearTimeout(_this.loadingDelayTimer); | ||
} | ||
if (_this.config.onSuccess) { | ||
_this.config.onSuccess(formattedResult, args); | ||
} | ||
var formattedResult = _this.config.formatResult ? _this.config.formatResult(res) : res; | ||
return formattedResult; | ||
_this.setState({ | ||
data: formattedResult, | ||
error: undefined, | ||
loading: false | ||
}); | ||
if (_this.config.onSuccess) { | ||
_this.config.onSuccess(formattedResult, args); | ||
} | ||
}).catch(function (error) { | ||
if (!_this.unmountedFlag && currentCount === _this.count) { | ||
if (_this.loadingDelayTimer) { | ||
clearTimeout(_this.loadingDelayTimer); | ||
} | ||
_this.setState({ | ||
data: undefined, | ||
error: error, | ||
loading: false | ||
}); | ||
return formattedResult; | ||
} | ||
})["catch"](function (error) { | ||
if (!_this.unmountedFlag && currentCount === _this.count) { | ||
if (_this.loadingDelayTimer) { | ||
clearTimeout(_this.loadingDelayTimer); | ||
} | ||
if (_this.config.onError) { | ||
_this.config.onError(error, args); | ||
} | ||
_this.setState({ | ||
data: undefined, | ||
error: error, | ||
loading: false | ||
}); | ||
console.error(error); | ||
return error; // throw error; | ||
if (_this.config.onError) { | ||
_this.config.onError(error, args); | ||
} | ||
}).finally(function () { | ||
if (!_this.unmountedFlag && currentCount === _this.count) { | ||
if (_this.config.pollingInterval) { | ||
// 如果屏幕隐藏,并且 !pollingWhenHidden, 则停止轮询,并记录 flag,等 visible 时,继续轮询 | ||
if (!(0, _utils.isDocumentVisible)() && !_this.config.pollingWhenHidden) { | ||
_this.pollingWhenVisibleFlag = true; | ||
return; | ||
} | ||
_this.pollingTimer = setTimeout(function () { | ||
_this._run.apply(_this, args); | ||
}, _this.config.pollingInterval); | ||
console.error(error); | ||
return error; // throw error; | ||
} | ||
})["finally"](function () { | ||
if (!_this.unmountedFlag && currentCount === _this.count) { | ||
if (_this.config.pollingInterval) { | ||
// 如果屏幕隐藏,并且 !pollingWhenHidden, 则停止轮询,并记录 flag,等 visible 时,继续轮询 | ||
if (!utils_1.isDocumentVisible() && !_this.config.pollingWhenHidden) { | ||
_this.pollingWhenVisibleFlag = true; | ||
return; | ||
} | ||
_this.pollingTimer = setTimeout(function () { | ||
_this._run.apply(_this, args); | ||
}, _this.config.pollingInterval); | ||
} | ||
}); | ||
} | ||
}, { | ||
key: "run", | ||
value: function run() { | ||
if (this.debounceRun) { | ||
this.debounceRun.apply(this, arguments); // TODO 如果 options 存在 debounceInterval,或 throttleInterval,则 run 和 refresh 不会返回 Promise。 带类型需要修复后,此处变成 return;。 | ||
return Promise.resolve(null); | ||
} | ||
}); | ||
}; | ||
if (this.throttleRun) { | ||
this.throttleRun.apply(this, arguments); | ||
return Promise.resolve(null); | ||
} | ||
_proto.run = function run() { | ||
if (this.debounceRun) { | ||
this.debounceRun.apply(this, arguments); // TODO 如果 options 存在 debounceInterval,或 throttleInterval,则 run 和 refresh 不会返回 Promise。 带类型需要修复后,此处变成 return;。 | ||
return this._run.apply(this, arguments); | ||
return Promise.resolve(null); | ||
} | ||
}, { | ||
key: "cancel", | ||
value: function cancel() { | ||
if (this.debounceRun) { | ||
this.debounceRun.cancel(); | ||
} | ||
if (this.throttleRun) { | ||
this.throttleRun.cancel(); | ||
} | ||
if (this.throttleRun) { | ||
this.throttleRun.apply(this, arguments); | ||
return Promise.resolve(null); | ||
} | ||
if (this.loadingDelayTimer) { | ||
clearTimeout(this.loadingDelayTimer); | ||
} | ||
return this._run.apply(this, arguments); | ||
}; | ||
if (this.pollingTimer) { | ||
clearTimeout(this.pollingTimer); | ||
} | ||
_proto.cancel = function cancel() { | ||
if (this.debounceRun) { | ||
this.debounceRun.cancel(); | ||
} | ||
this.pollingWhenVisibleFlag = false; | ||
this.count += 1; | ||
this.setState({ | ||
loading: false | ||
}); | ||
if (this.throttleRun) { | ||
this.throttleRun.cancel(); | ||
} | ||
}, { | ||
key: "refresh", | ||
value: function refresh() { | ||
return this.run.apply(this, _toConsumableArray(this.state.params)); | ||
if (this.loadingDelayTimer) { | ||
clearTimeout(this.loadingDelayTimer); | ||
} | ||
}, { | ||
key: "rePolling", | ||
value: function rePolling() { | ||
if (this.pollingWhenVisibleFlag) { | ||
this.pollingWhenVisibleFlag = false; | ||
this.refresh(); | ||
} | ||
if (this.pollingTimer) { | ||
clearTimeout(this.pollingTimer); | ||
} | ||
}, { | ||
key: "mutate", | ||
value: function mutate(data) { | ||
if (typeof data === 'function') { | ||
this.setState({ | ||
// eslint-disable-next-line react/no-access-state-in-setstate | ||
data: data(this.state.data) || {} | ||
}); | ||
} else { | ||
this.setState({ | ||
data: data | ||
}); | ||
} | ||
this.pollingWhenVisibleFlag = false; | ||
this.count += 1; | ||
this.setState({ | ||
loading: false | ||
}); | ||
}; | ||
_proto.refresh = function refresh() { | ||
return this.run.apply(this, this.state.params); | ||
}; | ||
_proto.rePolling = function rePolling() { | ||
if (this.pollingWhenVisibleFlag) { | ||
this.pollingWhenVisibleFlag = false; | ||
this.refresh(); | ||
} | ||
}, { | ||
key: "unmount", | ||
value: function unmount() { | ||
this.unmountedFlag = true; | ||
this.cancel(); | ||
this.unsubscribe.forEach(function (s) { | ||
s(); | ||
}; | ||
_proto.mutate = function mutate(data) { | ||
if (typeof data === 'function') { | ||
this.setState({ | ||
// eslint-disable-next-line react/no-access-state-in-setstate | ||
data: data(this.state.data) || {} | ||
}); | ||
} else { | ||
this.setState({ | ||
data: data | ||
}); | ||
} | ||
}]); | ||
}; | ||
_proto.unmount = function unmount() { | ||
this.unmountedFlag = true; | ||
this.cancel(); | ||
this.unsubscribe.forEach(function (s) { | ||
s(); | ||
}); | ||
}; | ||
return Fetch; | ||
@@ -325,8 +283,8 @@ }(); | ||
ready = _options$ready === void 0 ? true : _options$ready; | ||
var newstFetchKey = (0, _react.useRef)(DEFAULT_KEY); // 持久化一些函数 | ||
var newstFetchKey = react_1.useRef(DEFAULT_KEY); // 持久化一些函数 | ||
var servicePersist = (0, _usePersistFn.default)(service); | ||
var onSuccessPersist = (0, _usePersistFn.default)(onSuccess); | ||
var onErrorPersist = (0, _usePersistFn.default)(onError); | ||
var fetchKeyPersist = (0, _usePersistFn.default)(fetchKey); | ||
var servicePersist = usePersistFn_1["default"](service); | ||
var onSuccessPersist = usePersistFn_1["default"](onSuccess); | ||
var onErrorPersist = usePersistFn_1["default"](onError); | ||
var fetchKeyPersist = usePersistFn_1["default"](fetchKey); | ||
var formatResult; | ||
@@ -339,3 +297,3 @@ | ||
var formatResultPersist = (0, _usePersistFn.default)(formatResult); | ||
var formatResultPersist = usePersistFn_1["default"](formatResult); | ||
var config = { | ||
@@ -353,14 +311,14 @@ formatResult: formatResultPersist, | ||
}; | ||
var subscribe = (0, _usePersistFn.default)(function (key, data) { | ||
var subscribe = usePersistFn_1["default"](function (key, data) { | ||
setFeches(function (s) { | ||
// eslint-disable-next-line no-param-reassign | ||
s[key] = data; | ||
return _objectSpread({}, s); | ||
return Object.assign({}, s); | ||
}); | ||
}, []); | ||
var _useState = (0, _react.useState)(function () { | ||
var _react_1$useState = react_1.useState(function () { | ||
// 如果有 缓存,则从缓存中读数据 | ||
if (cacheKey) { | ||
var cache = (0, _cache.getCache)(cacheKey); | ||
var cache = cache_1.getCache(cacheKey); | ||
@@ -388,10 +346,9 @@ if (cache) { | ||
}), | ||
_useState2 = _slicedToArray(_useState, 2), | ||
fetches = _useState2[0], | ||
setFeches = _useState2[1]; | ||
fetches = _react_1$useState[0], | ||
setFeches = _react_1$useState[1]; | ||
var fetchesRef = (0, _react.useRef)(fetches); | ||
var fetchesRef = react_1.useRef(fetches); | ||
fetchesRef.current = fetches; | ||
var readyMemoryParams = (0, _react.useRef)(); | ||
var run = (0, _react.useCallback)(function () { | ||
var readyMemoryParams = react_1.useRef(); | ||
var run = react_1.useCallback(function () { | ||
var _currentFetch; | ||
@@ -427,3 +384,3 @@ | ||
s[currentFetchKey] = currentFetch; | ||
return _objectSpread({}, s); | ||
return Object.assign({}, s); | ||
}); | ||
@@ -434,8 +391,8 @@ } | ||
}, [fetchKey, subscribe, ready]); | ||
var runRef = (0, _react.useRef)(run); | ||
var runRef = react_1.useRef(run); | ||
runRef.current = run; // cache | ||
(0, _react.useEffect)(function () { | ||
react_1.useEffect(function () { | ||
if (cacheKey) { | ||
(0, _cache.setCache)(cacheKey, { | ||
cache_1.setCache(cacheKey, { | ||
fetches: fetches, | ||
@@ -447,7 +404,7 @@ newstFetchKey: newstFetchKey.current | ||
var hasTriggeredByReady = (0, _react.useRef)(false); | ||
(0, _useUpdateEffect.default)(function () { | ||
var hasTriggeredByReady = react_1.useRef(false); | ||
useUpdateEffect_1["default"](function () { | ||
if (ready) { | ||
if (!hasTriggeredByReady.current && readyMemoryParams.current) { | ||
runRef.current.apply(runRef, _toConsumableArray(readyMemoryParams.current)); | ||
runRef.current.apply(runRef, readyMemoryParams.current); | ||
} | ||
@@ -459,3 +416,3 @@ | ||
(0, _react.useEffect)(function () { | ||
react_1.useEffect(function () { | ||
if (!manual) { | ||
@@ -470,3 +427,3 @@ // 如果有缓存 | ||
// 第一次默认执行,可以通过 defaultParams 设置参数 | ||
runRef.current.apply(runRef, _toConsumableArray(defaultParams)); | ||
runRef.current.apply(runRef, defaultParams); | ||
} | ||
@@ -476,3 +433,3 @@ } | ||
var reset = (0, _react.useCallback)(function () { | ||
var reset = react_1.useCallback(function () { | ||
Object.values(fetchesRef.current).forEach(function (f) { | ||
@@ -487,3 +444,3 @@ f.unmount(); | ||
(0, _useUpdateEffect.default)(function () { | ||
useUpdateEffect_1["default"](function () { | ||
if (!manual) { | ||
@@ -495,5 +452,5 @@ /* 全部重新执行 */ | ||
} | ||
}, _toConsumableArray(refreshDeps)); // 卸载组件触发 | ||
}, [].concat(refreshDeps)); // 卸载组件触发 | ||
(0, _react.useEffect)(function () { | ||
react_1.useEffect(function () { | ||
return function () { | ||
@@ -505,8 +462,8 @@ Object.values(fetchesRef.current).forEach(function (f) { | ||
}, []); | ||
var notExecutedWarning = (0, _react.useCallback)(function (name) { | ||
var notExecutedWarning = react_1.useCallback(function (name) { | ||
return function () { | ||
throw new Error("Cannot call ".concat(name, " when service not executed once.")); | ||
throw new Error("Cannot call " + name + " when service not executed once."); | ||
}; | ||
}, []); | ||
return _objectSpread({ | ||
return Object.assign(Object.assign({ | ||
loading: ready && !manual || defaultLoading, | ||
@@ -519,3 +476,3 @@ data: initialData, | ||
mutate: notExecutedWarning('mutate') | ||
}, fetches[newstFetchKey.current] || {}, { | ||
}, fetches[newstFetchKey.current] || {}), { | ||
run: run, | ||
@@ -527,3 +484,2 @@ fetches: fetches, | ||
var _default = useAsync; | ||
exports.default = _default; | ||
exports["default"] = useAsync; |
@@ -6,40 +6,11 @@ "use strict"; | ||
}); | ||
exports.default = void 0; | ||
var _react = require("react"); | ||
var tslib_1 = require("tslib"); | ||
var _useAsync = _interopRequireDefault(require("./useAsync")); | ||
var react_1 = require("react"); | ||
var _useUpdateEffect = _interopRequireDefault(require("./utils/useUpdateEffect")); | ||
var useAsync_1 = tslib_1.__importDefault(require("./useAsync")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var useUpdateEffect_1 = tslib_1.__importDefault(require("./utils/useUpdateEffect")); | ||
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } | ||
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } | ||
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } | ||
function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } | ||
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } | ||
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } | ||
function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } | ||
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } | ||
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } | ||
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } | ||
function useLoadMore(service, options) { | ||
@@ -53,10 +24,9 @@ var _options$refreshDeps = options.refreshDeps, | ||
fetchKey = options.fetchKey, | ||
restOptions = _objectWithoutProperties(options, ["refreshDeps", "ref", "isNoMore", "threshold", "fetchKey"]); | ||
restOptions = tslib_1.__rest(options, ["refreshDeps", "ref", "isNoMore", "threshold", "fetchKey"]); | ||
var _useState = (0, _react.useState)(false), | ||
_useState2 = _slicedToArray(_useState, 2), | ||
loadingMore = _useState2[0], | ||
setLoadingMore = _useState2[1]; | ||
var _react_1$useState = react_1.useState(false), | ||
loadingMore = _react_1$useState[0], | ||
setLoadingMore = _react_1$useState[1]; | ||
(0, _react.useEffect)(function () { | ||
react_1.useEffect(function () { | ||
if (options.fetchKey) { | ||
@@ -66,7 +36,7 @@ console.warn("useRequest loadMore mode don't need fetchKey!"); | ||
}, []); | ||
var result = (0, _useAsync.default)(service, _objectSpread({}, restOptions, { | ||
var result = useAsync_1["default"](service, Object.assign(Object.assign({}, restOptions), { | ||
fetchKey: function fetchKey(d) { | ||
var _d$list; | ||
var _a; | ||
return (d === null || d === void 0 ? void 0 : (_d$list = d.list) === null || _d$list === void 0 ? void 0 : _d$list.length) || 0; | ||
return ((_a = d === null || d === void 0 ? void 0 : d.list) === null || _a === void 0 ? void 0 : _a.length) || 0; | ||
}, | ||
@@ -87,15 +57,12 @@ onSuccess: function onSuccess() { | ||
fetches = result.fetches; | ||
var reload = (0, _react.useCallback)(function () { | ||
var reload = react_1.useCallback(function () { | ||
reset(); | ||
var _params = _toArray(params), | ||
restParams = _params.slice(1); | ||
run.apply(void 0, [undefined].concat(_toConsumableArray(restParams))); | ||
var restParams = params.slice(1); | ||
run.apply(void 0, [undefined].concat(restParams)); | ||
}, [run, reset, params]); | ||
var reloadRef = (0, _react.useRef)(reload); | ||
var reloadRef = react_1.useRef(reload); | ||
reloadRef.current = reload; | ||
/* loadMore 场景下,如果 refreshDeps 变化,重置到第一页 */ | ||
(0, _useUpdateEffect.default)(function () { | ||
useUpdateEffect_1["default"](function () { | ||
/* 只有自动执行的场景, refreshDeps 才有效 */ | ||
@@ -105,4 +72,4 @@ if (!options.manual) { | ||
} | ||
}, _toConsumableArray(refreshDeps)); | ||
var dataGroup = (0, _react.useMemo)(function () { | ||
}, [].concat(refreshDeps)); | ||
var dataGroup = react_1.useMemo(function () { | ||
var listGroup = []; // 在 loadMore 时,不希望清空上一次的 data。需要把最后一个 非 loading 的请求 data,放回去。 | ||
@@ -112,8 +79,6 @@ | ||
Object.values(fetches).forEach(function (h) { | ||
var _h$data; | ||
var _a, _b; | ||
if ((_h$data = h.data) === null || _h$data === void 0 ? void 0 : _h$data.list) { | ||
var _h$data2; | ||
listGroup = listGroup.concat((_h$data2 = h.data) === null || _h$data2 === void 0 ? void 0 : _h$data2.list); | ||
if ((_a = h.data) === null || _a === void 0 ? void 0 : _a.list) { | ||
listGroup = listGroup.concat((_b = h.data) === null || _b === void 0 ? void 0 : _b.list); | ||
} | ||
@@ -125,3 +90,3 @@ | ||
}); | ||
return _objectSpread({}, lastNoLoadingData, { | ||
return Object.assign(Object.assign({}, lastNoLoadingData), { | ||
list: listGroup | ||
@@ -131,3 +96,3 @@ }); | ||
var noMore = isNoMore ? !loading && !loadingMore && isNoMore(dataGroup) : false; | ||
var loadMore = (0, _react.useCallback)(function () { | ||
var loadMore = react_1.useCallback(function () { | ||
if (noMore) { | ||
@@ -138,11 +103,8 @@ return; | ||
setLoadingMore(true); | ||
var _params2 = _toArray(params), | ||
restParams = _params2.slice(1); | ||
run.apply(void 0, [dataGroup].concat(_toConsumableArray(restParams))); | ||
var restParams = params.slice(1); | ||
run.apply(void 0, [dataGroup].concat(restParams)); | ||
}, [noMore, run, dataGroup, params]); | ||
/* 上拉加载的方法 */ | ||
var scrollMethod = (0, _react.useCallback)(function () { | ||
var scrollMethod = react_1.useCallback(function () { | ||
if (loading || loadingMore || !ref || !ref.current) { | ||
@@ -158,3 +120,3 @@ return; | ||
(0, _react.useEffect)(function () { | ||
react_1.useEffect(function () { | ||
if (!ref || !ref.current) { | ||
@@ -171,3 +133,3 @@ return function () {}; | ||
}, [scrollMethod]); | ||
return _objectSpread({}, result, { | ||
return Object.assign(Object.assign({}, result), { | ||
data: dataGroup, | ||
@@ -182,3 +144,2 @@ reload: reload, | ||
var _default = useLoadMore; | ||
exports.default = _default; | ||
exports["default"] = useLoadMore; |
@@ -6,36 +6,11 @@ "use strict"; | ||
}); | ||
exports.default = void 0; | ||
var _react = require("react"); | ||
var tslib_1 = require("tslib"); | ||
var _useAsync2 = _interopRequireDefault(require("./useAsync")); | ||
var react_1 = require("react"); | ||
var _useUpdateEffect = _interopRequireDefault(require("./utils/useUpdateEffect")); | ||
var useAsync_1 = tslib_1.__importDefault(require("./useAsync")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var useUpdateEffect_1 = tslib_1.__importDefault(require("./utils/useUpdateEffect")); | ||
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } | ||
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } | ||
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } | ||
function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } | ||
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } | ||
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } | ||
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } | ||
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } | ||
function usePaginated(service, options) { | ||
@@ -48,5 +23,5 @@ var paginated = options.paginated, | ||
fetchKey = options.fetchKey, | ||
restOptions = _objectWithoutProperties(options, ["paginated", "defaultPageSize", "refreshDeps", "fetchKey"]); | ||
restOptions = tslib_1.__rest(options, ["paginated", "defaultPageSize", "refreshDeps", "fetchKey"]); | ||
(0, _react.useEffect)(function () { | ||
react_1.useEffect(function () { | ||
if (fetchKey) { | ||
@@ -57,3 +32,3 @@ console.error('useRequest pagination\'s fetchKey will not work!'); | ||
var _useAsync = (0, _useAsync2.default)(service, _objectSpread({ | ||
var _a = useAsync_1["default"](service, Object.assign({ | ||
defaultParams: [{ | ||
@@ -64,7 +39,7 @@ current: 1, | ||
}, restOptions)), | ||
data = _useAsync.data, | ||
params = _useAsync.params, | ||
run = _useAsync.run, | ||
loading = _useAsync.loading, | ||
rest = _objectWithoutProperties(_useAsync, ["data", "params", "run", "loading"]); | ||
data = _a.data, | ||
params = _a.params, | ||
run = _a.run, | ||
loading = _a.loading, | ||
rest = tslib_1.__rest(_a, ["data", "params", "run", "loading"]); | ||
@@ -82,14 +57,12 @@ var _ref = params && params[0] ? params[0] : {}, | ||
var runChangePaination = (0, _react.useCallback)(function (paginationParams) { | ||
var _params = _toArray(params), | ||
oldPaginationParams = _params[0], | ||
restParams = _params.slice(1); | ||
run.apply(void 0, [_objectSpread({}, oldPaginationParams, {}, paginationParams)].concat(_toConsumableArray(restParams))); | ||
var runChangePaination = react_1.useCallback(function (paginationParams) { | ||
var oldPaginationParams = params[0], | ||
restParams = params.slice(1); | ||
run.apply(void 0, [Object.assign(Object.assign({}, oldPaginationParams), paginationParams)].concat(restParams)); | ||
}, [run, params]); | ||
var total = (data === null || data === void 0 ? void 0 : data.total) || 0; | ||
var totalPage = (0, _react.useMemo)(function () { | ||
var totalPage = react_1.useMemo(function () { | ||
return Math.ceil(total / pageSize); | ||
}, [pageSize, total]); | ||
var onChange = (0, _react.useCallback)(function (c, p) { | ||
var onChange = react_1.useCallback(function (c, p) { | ||
var toCurrent = c <= 0 ? 1 : c; | ||
@@ -108,13 +81,13 @@ var toPageSize = p <= 0 ? 1 : p; | ||
}, [total, runChangePaination]); | ||
var changeCurrent = (0, _react.useCallback)(function (c) { | ||
var changeCurrent = react_1.useCallback(function (c) { | ||
onChange(c, pageSize); | ||
}, [onChange, pageSize]); | ||
var changePageSize = (0, _react.useCallback)(function (p) { | ||
var changePageSize = react_1.useCallback(function (p) { | ||
onChange(current, p); | ||
}, [onChange, current]); | ||
var changeCurrentRef = (0, _react.useRef)(changeCurrent); | ||
var changeCurrentRef = react_1.useRef(changeCurrent); | ||
changeCurrentRef.current = changeCurrent; | ||
/* 分页场景下,如果 refreshDeps 变化,重置分页 */ | ||
(0, _useUpdateEffect.default)(function () { | ||
useUpdateEffect_1["default"](function () { | ||
/* 只有自动执行的场景, refreshDeps 才有效 */ | ||
@@ -124,5 +97,5 @@ if (!options.manual) { | ||
} | ||
}, _toConsumableArray(refreshDeps)); // 表格翻页 排序 筛选等 | ||
}, [].concat(refreshDeps)); // 表格翻页 排序 筛选等 | ||
var changeTable = (0, _react.useCallback)(function (p, f, s) { | ||
var changeTable = react_1.useCallback(function (p, f, s) { | ||
runChangePaination({ | ||
@@ -135,3 +108,3 @@ current: p.current, | ||
}, [filters, sorter, runChangePaination]); | ||
return _objectSpread({ | ||
return Object.assign({ | ||
loading: loading, | ||
@@ -165,3 +138,2 @@ data: data, | ||
var _default = usePaginated; | ||
exports.default = _default; | ||
exports["default"] = usePaginated; |
@@ -6,16 +6,9 @@ "use strict"; | ||
}); | ||
exports.default = void 0; | ||
var _umiRequest = _interopRequireDefault(require("umi-request")); | ||
var tslib_1 = require("tslib"); | ||
var _useAsync = _interopRequireDefault(require("./useAsync")); | ||
var umi_request_1 = tslib_1.__importDefault(require("umi-request")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var useAsync_1 = tslib_1.__importDefault(require("./useAsync")); | ||
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } | ||
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } | ||
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } | ||
function useRequest(service, options) { | ||
@@ -26,10 +19,10 @@ var promiseService; | ||
promiseService = function promiseService() { | ||
return (0, _umiRequest.default)(service); | ||
return umi_request_1["default"](service); | ||
}; | ||
} else if (_typeof(service) === 'object') { | ||
} else if (typeof service === 'object') { | ||
var url = service.url, | ||
rest = _objectWithoutProperties(service, ["url"]); | ||
rest = tslib_1.__rest(service, ["url"]); | ||
promiseService = function promiseService() { | ||
return (0, _umiRequest.default)(url, rest); | ||
return umi_request_1["default"](url, rest); | ||
}; | ||
@@ -46,10 +39,10 @@ } else { | ||
if (typeof result === 'string') { | ||
(0, _umiRequest.default)(result).then(function (data) { | ||
umi_request_1["default"](result).then(function (data) { | ||
resolve(data); | ||
}); | ||
} else if (_typeof(result) === 'object') { | ||
} else if (typeof result === 'object') { | ||
var _url = result.url, | ||
_rest = _objectWithoutProperties(result, ["url"]); | ||
_rest = tslib_1.__rest(result, ["url"]); | ||
(0, _umiRequest.default)(_url, _rest).then(function (data) { | ||
umi_request_1["default"](_url, _rest).then(function (data) { | ||
resolve(data); | ||
@@ -62,6 +55,5 @@ }); | ||
return (0, _useAsync.default)(promiseService, options); | ||
return useAsync_1["default"](promiseService, options); | ||
} | ||
var _default = useRequest; | ||
exports.default = _default; | ||
exports["default"] = useRequest; |
@@ -27,7 +27,7 @@ "use strict"; | ||
var getCache = function getCache(key) { | ||
var _cache$key; | ||
var _a; | ||
return (_cache$key = cache[key]) === null || _cache$key === void 0 ? void 0 : _cache$key.data; | ||
return (_a = cache[key]) === null || _a === void 0 ? void 0 : _a.data; | ||
}; | ||
exports.getCache = getCache; |
@@ -6,4 +6,3 @@ "use strict"; | ||
}); | ||
exports.isDocumentVisible = isDocumentVisible; | ||
exports.isOnline = isOnline; | ||
exports.isOnline = exports.isDocumentVisible = void 0; | ||
@@ -18,2 +17,4 @@ function isDocumentVisible() { | ||
exports.isDocumentVisible = isDocumentVisible; | ||
function isOnline() { | ||
@@ -25,2 +26,4 @@ if (typeof navigator.onLine !== 'undefined') { | ||
return true; | ||
} | ||
} | ||
exports.isOnline = isOnline; |
@@ -6,3 +6,2 @@ "use strict"; | ||
}); | ||
exports.default = limit; | ||
@@ -19,2 +18,4 @@ function limit(fn, timespan) { | ||
}; | ||
} | ||
} | ||
exports["default"] = limit; |
@@ -1,2 +0,2 @@ | ||
declare function usePersistFn(fn: any, dependencies?: any): ((...args: any[]) => any) | undefined; | ||
declare function usePersistFn(fn: any, dependencies?: any): (...args: any[]) => any; | ||
export default usePersistFn; |
@@ -6,23 +6,17 @@ "use strict"; | ||
}); | ||
exports.default = void 0; | ||
var _react = require("react"); | ||
var react_1 = require("react"); | ||
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } | ||
function usePersistFn(fn, dependencies) { | ||
if (dependencies === void 0) { | ||
dependencies = []; | ||
} | ||
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } | ||
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } | ||
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } | ||
function usePersistFn(fn) { | ||
var dependencies = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; | ||
var ref = (0, _react.useRef)(function () { | ||
var ref = react_1.useRef(function () { | ||
throw new Error('Cannot call an event handler while rendering.'); | ||
}); | ||
(0, _react.useEffect)(function () { | ||
react_1.useEffect(function () { | ||
ref.current = fn; | ||
}, [fn].concat(_toConsumableArray(dependencies))); | ||
var persist = (0, _react.useCallback)(function () { | ||
}, [fn].concat(dependencies)); | ||
var persist = react_1.useCallback(function () { | ||
var refFn = ref.current; | ||
@@ -42,3 +36,2 @@ | ||
var _default = usePersistFn; | ||
exports.default = _default; | ||
exports["default"] = usePersistFn; |
@@ -6,9 +6,8 @@ "use strict"; | ||
}); | ||
exports.default = void 0; | ||
var _react = require("react"); | ||
var react_1 = require("react"); | ||
var useUpdateEffect = function useUpdateEffect(effect, deps) { | ||
var isMounted = (0, _react.useRef)(false); | ||
(0, _react.useEffect)(function () { | ||
var isMounted = react_1.useRef(false); | ||
react_1.useEffect(function () { | ||
if (!isMounted.current) { | ||
@@ -22,3 +21,2 @@ isMounted.current = true; | ||
var _default = useUpdateEffect; | ||
exports.default = _default; | ||
exports["default"] = useUpdateEffect; |
@@ -5,8 +5,6 @@ "use strict"; | ||
value: true | ||
}); | ||
exports.default = void 0; | ||
}); // from swr | ||
var _index = require("./index"); | ||
var index_1 = require("./index"); | ||
// from swr | ||
var listeners = []; | ||
@@ -26,3 +24,3 @@ | ||
var revalidate = function revalidate() { | ||
if (!(0, _index.isDocumentVisible)() || !(0, _index.isOnline)()) return; | ||
if (!index_1.isDocumentVisible() || !index_1.isOnline()) return; | ||
@@ -41,3 +39,2 @@ for (var i = 0; i < listeners.length; i++) { | ||
var _default = subscribe; | ||
exports.default = _default; | ||
exports["default"] = subscribe; |
@@ -5,8 +5,6 @@ "use strict"; | ||
value: true | ||
}); | ||
exports.default = void 0; | ||
}); // from swr | ||
var _index = require("./index"); | ||
var index_1 = require("./index"); | ||
// from swr | ||
var listeners = []; | ||
@@ -26,3 +24,3 @@ | ||
var revalidate = function revalidate() { | ||
if (!(0, _index.isDocumentVisible)()) return; | ||
if (!index_1.isDocumentVisible()) return; | ||
@@ -40,3 +38,2 @@ for (var i = 0; i < listeners.length; i++) { | ||
var _default = subscribe; | ||
exports.default = _default; | ||
exports["default"] = subscribe; |
{ | ||
"name": "@ahooksjs/use-request", | ||
"version": "1.0.0", | ||
"version": "1.0.1-beta.1", | ||
"description": "React Hooks for fetching, caching and updating asynchronous data", | ||
@@ -20,4 +20,3 @@ "main": "./lib/index.js", | ||
"scripts": { | ||
"build:declaration": "tsc --declarationDir ./lib && tsc --declarationDir ./es && webpack-cli", | ||
"build:umd": "webpack-cli" | ||
"build": "gulp && webpack-cli" | ||
}, | ||
@@ -40,7 +39,6 @@ "publishConfig": { | ||
"devDependencies": { | ||
"ahooks": "^1.0.0", | ||
"axios": "^0.19.2", | ||
"umi-request": "^1.2.17" | ||
}, | ||
"gitHead": "4ea8f5c04c06eff2a33b2be473a8f7460909bebb" | ||
"gitHead": "561ebf0c820fa5fd6f1a8e83d6a8de3474254921" | ||
} |
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
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
2
102421
2206
2
7