@better-typed/react-hyper-fetch
Advanced tools
Comparing version 1.0.0-beta.1 to 1.0.0-beta.2
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),r=require("@better-typed/react-lifecycle-hooks"),t=require("@better-typed/hyper-fetch");function n(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function s(e,r){return function(e){if(Array.isArray(e))return e}(e)||function(e,r){var t=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=t){var n,s,i=[],a=!0,u=!1;try{for(t=t.call(e);!(a=(n=t.next()).done)&&(i.push(n.value),!r||i.length!==r);a=!0);}catch(e){u=!0,s=e}finally{try{a||null==t.return||t.return()}finally{if(u)throw s}}return i}}(e,r)||function(e,r){if(e){if("string"==typeof e)return n(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?n(e,r):void 0}}(e,r)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var a={data:null,error:null,loading:!0,status:null,refreshError:null,retryError:null,isRefreshed:!1,retries:0,timestamp:null,isOnline:!0,isFocused:!0};function u(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,n)}return t}function o(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?u(Object(t),!0).forEach((function(r){i(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):u(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}function c(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,n)}return t}function l(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?c(Object(t),!0).forEach((function(r){i(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):c(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}var d=(t,n,i,u)=>{var c=s(e.useState(+new Date),2)[1],d=e.useRef(((e,r)=>{var t,n,s,i;return o(o({},a),{},{data:(null==e||null===(t=e.response)||void 0===t?void 0:t[0])||a.data,error:(null==e||null===(n=e.response)||void 0===n?void 0:n[1])||a.error,status:(null==e||null===(s=e.response)||void 0===s?void 0:s[2])||a.status,retries:(null==e?void 0:e.retries)||a.retries,timestamp:(i=(null==e?void 0:e.timestamp)||a.timestamp,i?new Date(i):null),isOnline:r.manager.isOnline,isFocused:r.manager.isFocused})})(u,i)),f=e.useRef([]),v=e=>{f.current.find((r=>e.includes(r)))&&c(+new Date)};r.useDidMount((()=>{var e=i.manager.events.onFocus((()=>{d.current.isFocused=!0,v(["isFocused"])})),r=i.manager.events.onBlur((()=>{d.current.isFocused=!1,v(["isFocused"])})),t=i.manager.events.onOnline((()=>{d.current.isOnline=!0,v(["isOnline"])})),n=i.manager.events.onOffline((()=>{d.current.isOnline=!1,v(["isOnline"])}));return()=>{e(),r(),t(),n()}}));var h={setCacheData:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r)i.cache.set(l({cacheKey:t,requestKey:n},e));else{var s={data:e.response[0],error:e.response[1],status:e.response[2],retries:e.retries,timestamp:new Date(e.timestamp),retryError:e.retryError,refreshError:e.refreshError,isRefreshed:e.isRefreshed,loading:!1};d.current=l(l({},d.current),s),v(Object.keys(s))}},setData:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[e,s.error,s.status],retries:s.retries,isRefreshed:s.isRefreshed})}else d.current.data=e,v(["data"])},setError:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,e,s.status],retries:s.retries,isRefreshed:s.isRefreshed})}else d.current.error=e,v(["error"])},setLoading:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];r?i.fetchQueue.events.setLoading(n,{isLoading:e,isRetry:!1,isRefreshed:!1,isRevalidated:!1}):(d.current.loading=e,v(["loading"]))},setStatus:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,s.error,e],retries:s.retries,isRefreshed:s.isRefreshed})}else d.current.status=e,v(["status"])},setRefreshed:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,s.error,s.status],retries:s.retries,isRefreshed:e})}else d.current.isRefreshed=e,v(["isRefreshed"])},setRefreshError:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,e,s.status],retries:s.retries,isRefreshed:!0})}else d.current.refreshError=e,v(["refreshError"])},setRetryError:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,e,s.status],retries:s.retries,isRefreshed:!0})}else d.current.retryError=e,v(["retryError"])},setRetries:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,s.error,s.status],retries:e,isRefreshed:s.isRefreshed})}else d.current.retries=e,v(["retries"])},setTimestamp:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,s.error,s.status],retries:s.retries,isRefreshed:s.isRefreshed,timestamp:e?+e:void 0})}else d.current.timestamp=e,v(["timestamp"])}};return[d.current,h,e=>{f.current.push(e)}]},f=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:600,n=e.useRef({time:t,timer:null});n.current.time=t;var s=()=>{n.current.timer&&clearTimeout(n.current.timer),n.current.timer=null},i=e=>{s(),n.current.timer=setTimeout((()=>{n.current.timer=null,e()}),n.current.time)};return r.useWillUnmount(s),{debounce:i,resetDebounce:s,active:!!n.current.timer}},v=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:600,n=e.useRef({time:t,timer:null});n.current.time=t;var s=()=>{n.current.timer&&clearInterval(n.current.timer),n.current.timer=null},i=function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;s(),n.current.timer=setInterval((()=>{e()}),r<=0?n.current.time:r)};return r.useWillUnmount(s),{interval:i,resetInterval:s,active:!!n.current.timer}},h=(e,r,t)=>{if(r&&e&&t&&+e.timestamp+t>+new Date)return e},m=e=>e?{response:e,retries:0,timestamp:+new Date,isRefreshed:!1}:null,p=(e,r)=>!r||!!e&&+new Date>+r+e,g={dependencies:[],disabled:!1,dependencyTracking:!0,cacheOnMount:!0,revalidateOnMount:!1,initialData:null,refresh:!1,refreshTime:t.DateInterval.hour,refreshBlurred:!1,refreshOnTabBlur:!1,refreshOnTabFocus:!1,refreshOnReconnect:!1,cancelable:!1,debounce:!1,debounceTime:200*t.DateInterval.second,deepCompareFn:void 0,mapperFn:null,shouldThrow:!1};exports.useFetch=function(n){var i,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:g,u=a.dependencies,o=void 0===u?g.dependencies:u,c=a.disabled,l=void 0===c?g.disabled:c,y=a.dependencyTracking,b=void 0===y?g.dependencyTracking:y,O=a.cacheOnMount,R=void 0===O?g.cacheOnMount:O,D=a.revalidateOnMount,w=void 0===D?g.revalidateOnMount:D,j=a.initialData,E=void 0===j?g.initialData:j,F=a.refresh,T=void 0===F?g.refresh:F,K=a.refreshTime,P=void 0===K?g.refreshTime:K,S=a.refreshBlurred,q=void 0===S?g.refreshBlurred:S,M=a.refreshOnTabBlur,I=void 0===M?g.refreshOnTabBlur:M,k=a.refreshOnTabFocus,B=void 0===k?g.refreshOnTabFocus:k,C=a.refreshOnReconnect,U=void 0===C?g.refreshOnReconnect:C,A=a.debounce,L=void 0===A?g.debounce:A,x=a.debounceTime,Q=void 0===x?g.debounceTime:x,W=a.mapperFn,_=void 0===W?g.mapperFn:W,$=a.shouldThrow,z=void 0===$?g.shouldThrow:$,G=n.cacheTime,H=n.cacheKey,J=n.queueKey,N=f(Q),V=v(P),X=n.builder,Y=X.cache,Z=X.fetchQueue,ee=X.manager,re=X.commandManager,te=t.getCacheRequestKey(n),ne=e.useRef(h(Y.get(H,te),R,G)),se=e.useRef(p(G,null===(i=ne.current)||void 0===i?void 0:i.timestamp)),ie=e.useRef(se.current?m(E):ne.current),ae=d(H,te,n.builder,ie.current),ue=s(ae,3),oe=ue[0],ce=ue[1],le=ue[2],de=e.useState(!se.current),fe=s(de,2),ve=fe[0],he=fe[1],me=e.useRef(null),pe=e.useRef(null),ge=e.useRef(null),ye=e.useRef(null),be=e.useRef(null),Oe=e.useRef(null),Re=e.useRef(null),De=e.useRef(null),we=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:oe.isRefreshed,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=p(G,oe.timestamp);l||!t&&ve&&!e&&!r||Z.add(n,{isRefreshed:e,isRevalidated:r})},je=()=>{V.resetInterval();var e=oe.timestamp,r=e?Math.max(+e+P-+new Date):0;T&&V.interval((()=>{var e=Z.get(J),r=!n.builder.manager.isFocused&&q||n.builder.manager.isFocused;!e&&r&&(we(!0),V.resetInterval())}),r)},Ee=e=>{if(e){var r,t,n;if(e[0])null==pe||null===(t=pe.current)||void 0===t||t.call(pe,e[0]);if(e[1])if(null==ge||null===(n=ge.current)||void 0===n||n.call(ge,e[1]),z)throw{message:"Fetching Error.",error:e[1]};null==ye||null===(r=ye.current)||void 0===r||r.call(ye,e)}},Fe=e=>{ce.setCacheData(e,!1),Ee(e.response)},Te=()=>{if(!ve){var e=Y.get(H,te);e&&(ce.setCacheData(e,!1),he(!0))}ce.setRefreshed(!0,!1),ce.setTimestamp(new Date,!1),Ee([oe.data,oe.error,oe.status])},Ke=e=>{var r,t=e.isLoading,n=e.isRefreshed,s=e.isRetry,i=e.isRevalidated;ce.setLoading(t,!1),null===(r=me.current)||void 0===r||r.call(me,{isRefreshed:n,isRetry:s,isRevalidated:i})},Pe=()=>{we(!1,!0)},Se=e=>{e&&"string"==typeof e?n.builder.cache.events.revalidate(e):e&&e instanceof t.FetchCommand?n.builder.cache.events.revalidate(t.getCacheKey(e)):Pe()},qe=e=>{var r;null==Re||null===(r=Re.current)||void 0===r||r.call(Re,e)},Me=e=>{var r;null==De||null===(r=De.current)||void 0===r||r.call(De,e)},Ie=e=>{var r;null==be||null===(r=be.current)||void 0===r||r.call(be,e)},ke=e=>{var r;null==be||null===(r=be.current)||void 0===r||r.call(be,e)},Be=()=>{var e=ee.events.onFocus((()=>B&&we(!0))),r=ee.events.onBlur((()=>I&&we(!0))),t=ee.events.onOnline((()=>U&&we(!0))),n=re.events.onDownloadProgress(J,qe),s=re.events.onUploadProgress(J,Me),i=re.events.onRequestStart(J,Ie),a=re.events.onResponseStart(J,ke),u=Z.events.getLoading(te,Ke),o=Y.events.get(te,Fe),c=Y.events.getRefreshed(te,Te),l=Y.events.onRevalidate(te,Pe);return()=>{e(),r(),t(),n(),s(),i(),a(),u(),o(),c(),l()}},Ce=()=>_&&oe.data?_(oe.data):oe.data,Ue=()=>{b||Object.keys(oe).forEach((e=>le(e)))};return r.useDidMount((()=>{var e;return Ee(null===(e=ie.current)||void 0===e?void 0:e.response),Ue(),Be()})),r.useDidUpdate((()=>{ve&&L?N.debounce(we):we(!1,w)}),[...o,l],!0),r.useDidUpdate((()=>{je()}),[T,P,oe.timestamp],!0),{get data(){return le("data"),Ce()},get error(){return le("error"),oe.error},get loading(){return le("loading"),oe.loading},get status(){return le("status"),oe.status},get retryError(){return le("retryError"),oe.retryError},get refreshError(){return le("refreshError"),oe.refreshError},get isRefreshed(){return le("isRefreshed"),oe.isRefreshed},get retries(){return le("retries"),oe.retries},get timestamp(){return le("timestamp"),oe.timestamp},get isOnline(){return le("isOnline"),oe.isOnline},get isFocused(){return le("isFocused"),oe.isFocused},get isStale(){return p(G,oe.timestamp)},actions:ce,onRequest:e=>{me.current=e},onSuccess:e=>{pe.current=e},onError:e=>{ge.current=e},onFinished:e=>{ye.current=e},onRequestStart:e=>{be.current=e},onResponseStart:e=>{Oe.current=e},onDownloadProgress:e=>{Re.current=e},onUploadProgress:e=>{De.current=e},isRefreshingError:!!oe.error&&oe.isRefreshed,isDebouncing:N.active,refresh:Se}}; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),r=require("@better-typed/react-lifecycle-hooks"),t=require("@better-typed/hyper-fetch");function n(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function s(e,r){return function(e){if(Array.isArray(e))return e}(e)||function(e,r){var t=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=t){var n,s,i=[],a=!0,u=!1;try{for(t=t.call(e);!(a=(n=t.next()).done)&&(i.push(n.value),!r||i.length!==r);a=!0);}catch(e){u=!0,s=e}finally{try{a||null==t.return||t.return()}finally{if(u)throw s}}return i}}(e,r)||function(e,r){if(e){if("string"==typeof e)return n(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?n(e,r):void 0}}(e,r)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var a={data:null,error:null,loading:!0,status:null,refreshError:null,retryError:null,isRefreshed:!1,retries:0,timestamp:null,isOnline:!0,isFocused:!0};function u(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,n)}return t}function o(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?u(Object(t),!0).forEach((function(r){i(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):u(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}function l(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,n)}return t}function c(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?l(Object(t),!0).forEach((function(r){i(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):l(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}var d=(t,n,i,u)=>{var l=s(e.useState(+new Date),2)[1],d=e.useRef(((e,r)=>{var t,n,s,i;return o(o({},a),{},{data:(null==e||null===(t=e.response)||void 0===t?void 0:t[0])||a.data,error:(null==e||null===(n=e.response)||void 0===n?void 0:n[1])||a.error,status:(null==e||null===(s=e.response)||void 0===s?void 0:s[2])||a.status,retries:(null==e?void 0:e.retries)||a.retries,timestamp:(i=(null==e?void 0:e.timestamp)||a.timestamp,i?new Date(i):null),isOnline:r.manager.isOnline,isFocused:r.manager.isFocused})})(u,i)),v=e.useRef([]),f=e=>{v.current.find((r=>e.includes(r)))&&l(+new Date)};r.useDidMount((()=>{var e=i.manager.events.onFocus((()=>{d.current.isFocused=!0,f(["isFocused"])})),r=i.manager.events.onBlur((()=>{d.current.isFocused=!1,f(["isFocused"])})),t=i.manager.events.onOnline((()=>{d.current.isOnline=!0,f(["isOnline"])})),n=i.manager.events.onOffline((()=>{d.current.isOnline=!1,f(["isOnline"])}));return()=>{e(),r(),t(),n()}}));var h={setCacheData:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r)i.cache.set(c({cacheKey:t,requestKey:n},e));else{var s={data:e.response[0],error:e.response[1],status:e.response[2],retries:e.retries,timestamp:new Date(e.timestamp),retryError:e.retryError,refreshError:e.refreshError,isRefreshed:e.isRefreshed,loading:!1};d.current=c(c({},d.current),s),f(Object.keys(s))}},setData:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[e,s.error,s.status],retries:s.retries,isRefreshed:s.isRefreshed})}else d.current.data=e,f(["data"])},setError:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,e,s.status],retries:s.retries,isRefreshed:s.isRefreshed})}else d.current.error=e,f(["error"])},setLoading:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];r?i.fetchQueue.events.setLoading(n,{isLoading:e,isRetry:!1,isRefreshed:!1,isRevalidated:!1}):(d.current.loading=e,f(["loading"]))},setStatus:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,s.error,e],retries:s.retries,isRefreshed:s.isRefreshed})}else d.current.status=e,f(["status"])},setRefreshed:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,s.error,s.status],retries:s.retries,isRefreshed:e})}else d.current.isRefreshed=e,f(["isRefreshed"])},setRefreshError:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,e,s.status],retries:s.retries,isRefreshed:!0})}else d.current.refreshError=e,f(["refreshError"])},setRetryError:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,e,s.status],retries:s.retries,isRefreshed:!0})}else d.current.retryError=e,f(["retryError"])},setRetries:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,s.error,s.status],retries:e,isRefreshed:s.isRefreshed})}else d.current.retries=e,f(["retries"])},setTimestamp:function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(r){var s=d.current;i.cache.set({cacheKey:t,requestKey:n,response:[s.data,s.error,s.status],retries:s.retries,isRefreshed:s.isRefreshed,timestamp:e?+e:void 0})}else d.current.timestamp=e,f(["timestamp"])}};return[d.current,h,e=>{v.current.push(e)}]},v=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:600,n=e.useRef({time:t,timer:null});n.current.time=t;var s=()=>{n.current.timer&&clearTimeout(n.current.timer),n.current.timer=null},i=e=>{s(),n.current.timer=setTimeout((()=>{n.current.timer=null,e()}),n.current.time)};return r.useWillUnmount(s),{debounce:i,resetDebounce:s,active:!!n.current.timer}},f=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:600,n=e.useRef({time:t,timer:null});n.current.time=t;var s=()=>{n.current.timer&&clearInterval(n.current.timer),n.current.timer=null},i=function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;s(),n.current.timer=setInterval((()=>{e()}),r<=0?n.current.time:r)};return r.useWillUnmount(s),{interval:i,resetInterval:s,active:!!n.current.timer}},h=(e,r,t)=>{if(r&&e&&t&&+e.timestamp+t>+new Date)return e},m=e=>e?{response:e,retries:0,timestamp:+new Date,isRefreshed:!1}:null,g=(e,r)=>!r||!!e&&+new Date>+r+e,p={dependencies:[],disabled:!1,dependencyTracking:!0,cacheOnMount:!0,revalidateOnMount:!1,initialData:null,refresh:!1,refreshTime:t.DateInterval.hour,refreshBlurred:!1,refreshOnTabBlur:!1,refreshOnTabFocus:!1,refreshOnReconnect:!1,cancelable:!1,debounce:!1,debounceTime:400,deepCompareFn:void 0,responseDataModifierFn:null,shouldThrow:!1},y={disabled:!1,dependencyTracking:!0,cacheOnMount:!0,initialData:null,debounce:!1,debounceTime:400,suspense:!1,shouldThrow:!1,responseDataModifierFn:null,invalidate:[]};exports.useFetch=function(n){var i,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:p,u=a.dependencies,o=void 0===u?p.dependencies:u,l=a.disabled,c=void 0===l?p.disabled:l,y=a.dependencyTracking,R=void 0===y?p.dependencyTracking:y,b=a.cacheOnMount,O=void 0===b?p.cacheOnMount:b,D=a.revalidateOnMount,w=void 0===D?p.revalidateOnMount:D,E=a.initialData,F=void 0===E?p.initialData:E,T=a.refresh,j=void 0===T?p.refresh:T,P=a.refreshTime,S=void 0===P?p.refreshTime:P,K=a.refreshBlurred,q=void 0===K?p.refreshBlurred:K,M=a.refreshOnTabBlur,k=void 0===M?p.refreshOnTabBlur:M,C=a.refreshOnTabFocus,I=void 0===C?p.refreshOnTabFocus:C,L=a.refreshOnReconnect,U=void 0===L?p.refreshOnReconnect:L,B=a.debounce,A=void 0===B?p.debounce:B,x=a.debounceTime,Q=void 0===x?p.debounceTime:x,W=a.responseDataModifierFn,_=void 0===W?p.responseDataModifierFn:W,$=a.shouldThrow,z=void 0===$?p.shouldThrow:$,G=n.cacheTime,H=n.cacheKey,J=n.queueKey,N=v(Q),V=f(S),X=n.builder,Y=X.cache,Z=X.fetchQueue,ee=X.manager,re=X.commandManager,te=t.getCacheRequestKey(n),ne=e.useRef(h(Y.get(H,te),O,G)),se=e.useRef(g(G,null===(i=ne.current)||void 0===i?void 0:i.timestamp)),ie=e.useRef(se.current?m(F):ne.current),ae=d(H,te,n.builder,ie.current),ue=s(ae,3),oe=ue[0],le=ue[1],ce=ue[2],de=e.useState(!se.current),ve=s(de,2),fe=ve[0],he=ve[1],me=e.useRef(null),ge=e.useRef(null),pe=e.useRef(null),ye=e.useRef(null),Re=e.useRef(null),be=e.useRef(null),Oe=e.useRef(null),De=e.useRef(null),we=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:oe.isRefreshed,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=g(G,oe.timestamp);c||!t&&fe&&!e&&!r||Z.add(n,{isRefreshed:e,isRevalidated:r})},Ee=()=>{V.resetInterval();var e=oe.timestamp,r=e?Math.max(+e+S-+new Date):0;j&&V.interval((()=>{var e=Z.get(J),r=!n.builder.manager.isFocused&&q||n.builder.manager.isFocused;!e&&r&&(we(!0),V.resetInterval())}),r)},Fe=e=>{if(e){var r,t,n;if(e[0])null==ge||null===(t=ge.current)||void 0===t||t.call(ge,e[0]);if(e[1])if(null==pe||null===(n=pe.current)||void 0===n||n.call(pe,e[1]),z)throw{message:"Fetching Error.",error:e[1]};null==ye||null===(r=ye.current)||void 0===r||r.call(ye,e)}},Te=e=>{le.setCacheData(e,!1),Fe(e.response)},je=()=>{if(!fe){var e=Y.get(H,te);e&&(le.setCacheData(e,!1),he(!0))}le.setRefreshed(!0,!1),le.setTimestamp(new Date,!1),Fe([oe.data,oe.error,oe.status])},Pe=e=>{var r,t=e.isLoading,n=e.isRefreshed,s=e.isRetry,i=e.isRevalidated;le.setLoading(t,!1),null===(r=me.current)||void 0===r||r.call(me,{isRefreshed:n,isRetry:s,isRevalidated:i})},Se=()=>{we(!1,!0)},Ke=e=>{e&&"string"==typeof e?n.builder.cache.events.revalidate(e):e&&e instanceof t.FetchCommand?n.builder.cache.events.revalidate(t.getCacheKey(e)):Se()},qe=e=>{var r;null==Oe||null===(r=Oe.current)||void 0===r||r.call(Oe,e)},Me=e=>{var r;null==De||null===(r=De.current)||void 0===r||r.call(De,e)},ke=e=>{var r;null==Re||null===(r=Re.current)||void 0===r||r.call(Re,e)},Ce=e=>{var r;null==Re||null===(r=Re.current)||void 0===r||r.call(Re,e)},Ie=()=>{var e=ee.events.onFocus((()=>I&&we(!0))),r=ee.events.onBlur((()=>k&&we(!0))),t=ee.events.onOnline((()=>U&&we(!0))),n=re.events.onDownloadProgress(J,qe),s=re.events.onUploadProgress(J,Me),i=re.events.onRequestStart(J,ke),a=re.events.onResponseStart(J,Ce),u=Z.events.getLoading(te,Pe),o=Y.events.get(te,Te),l=Y.events.getRefreshed(te,je),c=Y.events.onRevalidate(te,Se);return()=>{e(),r(),t(),n(),s(),i(),a(),u(),o(),l(),c()}},Le=()=>_&&oe.data?_(oe.data):oe.data,Ue=()=>{R||Object.keys(oe).forEach((e=>ce(e)))};return r.useDidMount((()=>{var e;return Fe(null===(e=ie.current)||void 0===e?void 0:e.response),Ue(),Ie()})),r.useDidUpdate((()=>{fe&&A?N.debounce(we):we(!1,w)}),[...o,c],!0),r.useDidUpdate((()=>{Ee()}),[j,S,oe.timestamp],!0),{get data(){return ce("data"),Le()},get error(){return ce("error"),oe.error},get loading(){return ce("loading"),oe.loading},get status(){return ce("status"),oe.status},get retryError(){return ce("retryError"),oe.retryError},get refreshError(){return ce("refreshError"),oe.refreshError},get isRefreshed(){return ce("isRefreshed"),oe.isRefreshed},get retries(){return ce("retries"),oe.retries},get timestamp(){return ce("timestamp"),oe.timestamp},get isOnline(){return ce("isOnline"),oe.isOnline},get isFocused(){return ce("isFocused"),oe.isFocused},get isStale(){return g(G,oe.timestamp)},actions:le,onRequest:e=>{me.current=e},onSuccess:e=>{ge.current=e},onError:e=>{pe.current=e},onFinished:e=>{ye.current=e},onRequestStart:e=>{Re.current=e},onResponseStart:e=>{be.current=e},onDownloadProgress:e=>{Oe.current=e},onUploadProgress:e=>{De.current=e},isRefreshingError:!!oe.error&&oe.isRefreshed,isDebouncing:N.active,refresh:Ke}},exports.useSubmit=function(n){var i,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:y,u=a.disabled,o=void 0===u?y.disabled:u,l=a.dependencyTracking,c=void 0===l?y.dependencyTracking:l,v=a.cacheOnMount,f=void 0===v?y.cacheOnMount:v,p=a.initialData,R=void 0===p?y.initialData:p,b=a.shouldThrow,O=void 0===b?y.shouldThrow:b,D=a.responseDataModifierFn,w=void 0===D?y.responseDataModifierFn:D,E=n.cacheTime,F=n.cacheKey,T=n.queueKey,j=n.builder,P=j.cache,S=j.submitQueue,K=j.commandManager,q=t.getCacheRequestKey(n),M=e.useRef(h(P.get(F,q),f,E)),k=e.useRef(g(E,null===(i=M.current)||void 0===i?void 0:i.timestamp)),C=e.useRef(k.current?m(R):M.current),I=d(F,q,n.builder,C.current),L=s(I,3),U=L[0],B=L[1],A=L[2],x=e.useRef(null),Q=e.useRef(null),W=e.useRef(null),_=e.useRef(null),$=e.useRef(null),z=e.useRef(null),G=e.useRef(null),H=e.useRef(null),J=function(){var e=n,r=arguments.length<=0?void 0:arguments[0];null!=r&&r.data&&(e=e.setData(r.data)),null!=r&&r.params&&(e=e.setParams(r.params)),null!=r&&r.queryParams&&(e=e.setQueryParams(r.queryParams)),o||S.add(e)},N=e=>{if(e){var r,t,n;if(e[0])null==Q||null===(t=Q.current)||void 0===t||t.call(Q,e[0]);if(e[1])if(null==W||null===(n=W.current)||void 0===n||n.call(W,e[1]),O)throw{message:"Fetching Error.",error:e[1]};null==_||null===(r=_.current)||void 0===r||r.call(_,e)}},V=e=>{B.setCacheData(e,!1),N(e.response)},X=()=>{B.setRefreshed(!0,!1),B.setTimestamp(new Date,!1),N([U.data,U.error,U.status])},Y=e=>{var r,t=e.isLoading,n=e.isRetry;B.setLoading(t,!1),null===(r=x.current)||void 0===r||r.call(x,{isRetry:n})},Z=e=>{var r;null==G||null===(r=G.current)||void 0===r||r.call(G,e)},ee=e=>{var r;null==H||null===(r=H.current)||void 0===r||r.call(H,e)},re=e=>{var r;null==$||null===(r=$.current)||void 0===r||r.call($,e)},te=e=>{var r;null==$||null===(r=$.current)||void 0===r||r.call($,e)},ne=()=>{var e=K.events.onDownloadProgress(T,Z),r=K.events.onUploadProgress(T,ee),t=K.events.onRequestStart(T,re),n=K.events.onResponseStart(T,te),s=S.events.getLoading(T,Y),i=P.events.get(q,V),a=P.events.getRefreshed(q,X);return()=>{e(),r(),t(),n(),s(),i(),a()}},se=()=>w&&U.data?w(U.data):U.data,ie=()=>{c||Object.keys(U).forEach((e=>A(e)))};return r.useDidMount((()=>(ie(),ne()))),{submit:J,get data(){return A("data"),se()},get error(){return A("error"),U.error},get isSubmitting(){return A("loading"),U.loading},get status(){return A("status"),U.status},get retryError(){return A("retryError"),U.retryError},get retries(){return A("retries"),U.retries},get timestamp(){return A("timestamp"),U.timestamp},get isOnline(){return A("isOnline"),U.isOnline},get isFocused(){return A("isFocused"),U.isFocused},get isStale(){return g(E,U.timestamp)},actions:B,isDebouncing:!1,isRefreshed:!1,onRequest:e=>{x.current=e},onSuccess:e=>{Q.current=e},onError:e=>{W.current=e},onFinished:e=>{_.current=e},onRequestStart:e=>{$.current=e},onResponseStart:e=>{z.current=e},onDownloadProgress:e=>{G.current=e},onUploadProgress:e=>{H.current=e}}}; | ||
//# sourceMappingURL=index.cjs.js.map |
@@ -1,7 +0,2 @@ | ||
// export * from "./use-cache"; | ||
// export * from "./use-queue"; | ||
export * from "./use-fetch"; | ||
// export * from "./use-infinite-fetch"; | ||
// export * from "./use-call"; | ||
export * from "./use-submit"; |
@@ -18,6 +18,6 @@ import { DateInterval } from "@better-typed/hyper-fetch"; | ||
debounce: false, | ||
debounceTime: DateInterval.second * 200, | ||
debounceTime: 400, // milliseconds | ||
deepCompareFn: undefined, | ||
mapperFn: null, | ||
responseDataModifierFn: null, | ||
shouldThrow: false, | ||
}; |
@@ -51,3 +51,3 @@ import { useRef, useState } from "react"; | ||
debounceTime = useFetchDefaultOptions.debounceTime, | ||
mapperFn = useFetchDefaultOptions.mapperFn, | ||
responseDataModifierFn = useFetchDefaultOptions.responseDataModifierFn, | ||
shouldThrow = useFetchDefaultOptions.shouldThrow, | ||
@@ -221,3 +221,3 @@ }: UseFetchOptionsType<T, MapperResponse> = useFetchDefaultOptions, | ||
const handleData = () => { | ||
return mapperFn && state.data ? mapperFn(state.data) : state.data; | ||
return responseDataModifierFn && state.data ? responseDataModifierFn(state.data) : state.data; | ||
}; | ||
@@ -269,8 +269,4 @@ | ||
return { | ||
// ts bug somehow multiplies the typings required here | ||
get data(): (MapperResponse extends never ? ExtractResponse<T> : MapperResponse) extends never | ||
? ExtractResponse<T> | ||
: MapperResponse extends never | ||
? ExtractResponse<T> | ||
: MapperResponse { | ||
// necessary due to TS 4.5 restrictions on assignability of conditional types | ||
get data() { | ||
setRenderKey("data"); | ||
@@ -277,0 +273,0 @@ return handleData() as (MapperResponse extends never ? ExtractResponse<T> : MapperResponse) extends never |
@@ -30,3 +30,3 @@ import { | ||
shouldThrow?: boolean; | ||
mapperFn?: ((data: ExtractResponse<T>) => MapperResponse) | null; | ||
responseDataModifierFn?: ((data: ExtractResponse<T>) => MapperResponse) | null; | ||
}; | ||
@@ -33,0 +33,0 @@ |
@@ -1,1 +0,1 @@ | ||
// export * from "./use-submit.hooks"; | ||
export * from "./use-submit.hooks"; |
@@ -1,21 +0,13 @@ | ||
import { DateInterval } from "@better-typed/hyper-fetch"; | ||
// TODO - check whether cache should me settable from Command or useSubmit | ||
export const useSubmitDefaultOptions = { | ||
disabled: false, | ||
queueKey: "", | ||
invalidate: [], | ||
retry: false, | ||
retryTime: DateInterval.second, | ||
cacheTime: DateInterval.hour, | ||
cacheKey: "", | ||
cacheOnMount: true, | ||
initialCacheData: null, | ||
disabled: false, // disables submitting possibility | ||
dependencyTracking: true, // if true -> accessors rerender only when used. If false -> rerenders on every change | ||
cacheOnMount: true, // should use data from cache (?) on initialization - to be checked whether is useful | ||
initialData: null, | ||
debounce: false, | ||
cancelable: false, | ||
debounceTime: DateInterval.second * 200, | ||
deepCompareFn: null, | ||
mapperFn: null, | ||
shouldThrow: false, | ||
offline: false, | ||
debounceTime: 400, // milliseconds | ||
suspense: false, // TBD | ||
shouldThrow: false, // TBD | ||
responseDataModifierFn: null, | ||
invalidate: [], | ||
}; |
@@ -1,46 +0,246 @@ | ||
// import { FetchCommandInstance } from "middleware"; | ||
// import { useSubmitDefaultOptions } from "./use-submit.constants"; | ||
// import { UseSubmitOptionsType } from "./use-submit.types"; | ||
import { useRef } from "react"; | ||
import { | ||
ExtractResponse, | ||
FetchCommandInstance, | ||
getCacheRequestKey, | ||
FetchProgressType, | ||
ExtractError, | ||
ExtractFetchReturn, | ||
SubmitLoadingEventType, | ||
CacheValueType, | ||
} from "@better-typed/hyper-fetch"; | ||
import { useDidMount } from "@better-typed/react-lifecycle-hooks"; | ||
// export const useSubmit = <T extends FetchCommandInstance, MapperResponse>( | ||
// middleware: T, | ||
// { | ||
// disabled = useSubmitDefaultOptions.disabled, | ||
// queueKey = useSubmitDefaultOptions.queueKey, | ||
// invalidate = useSubmitDefaultOptions.invalidate, | ||
// retry = useSubmitDefaultOptions.retry, | ||
// retryTime = useSubmitDefaultOptions.retryTime, | ||
// cacheTime = useSubmitDefaultOptions.cacheTime, | ||
// cacheKey = useSubmitDefaultOptions.cacheKey, | ||
// cacheOnMount = useSubmitDefaultOptions.cacheOnMount, | ||
// initialCacheData = useSubmitDefaultOptions.initialCacheData, | ||
// initialData = useSubmitDefaultOptions.initialData, | ||
// debounce = useSubmitDefaultOptions.debounce, | ||
// debounceTime = useSubmitDefaultOptions.debounceTime, | ||
// cancelable = useSubmitDefaultOptions.cancelable, | ||
// deepCompareFn = useSubmitDefaultOptions.deepCompareFn, | ||
// mapperFn = useSubmitDefaultOptions.mapperFn, | ||
// shouldThrow = useSubmitDefaultOptions.shouldThrow, | ||
// offline = useSubmitDefaultOptions.offline, | ||
// }: UseSubmitOptionsType<T, MapperResponse> = useSubmitDefaultOptions, | ||
// ) => { | ||
// return { | ||
// ...state, | ||
// data: handleData() as any, | ||
// actions, | ||
// onSuccess: (callback: OnSuccessCallbackType<ExtractResponse<T>>) => { | ||
// onSuccessCallback.current = callback; | ||
// }, | ||
// onError: (callback: OnErrorCallbackType<ExtractError<T>>) => { | ||
// onErrorCallback.current = callback; | ||
// }, | ||
// onFinished: (callback: OnFinishedCallbackType<ExtractFetchReturn<T>>) => { | ||
// onFinishedCallback.current = callback; | ||
// }, | ||
// isRefreshed: state.isRefreshed, | ||
// isRefreshingError: !!state.error && state.isRefreshed, | ||
// isDebouncing: requestDebounce.active, | ||
// refresh: refreshFn, | ||
// submit, | ||
// }; | ||
// }; | ||
import { | ||
UseSubmitOptionsType, | ||
UseSubmitReturnType, | ||
OnSuccessCallbackType, | ||
OnErrorCallbackType, | ||
OnRequestCallbackType, | ||
OnFinishedCallbackType, | ||
OnStartCallbackType, | ||
OnProgressCallbackType, | ||
} from "./use-submit.types"; | ||
import { useSubmitDefaultOptions } from "./use-submit.constants"; | ||
import { getCacheState, getUseFetchInitialData, isStaleCacheData } from "../use-fetch/use-fetch.utils"; | ||
import { useDependentState } from "../use-dependent-state/use-dependent-state.hooks"; | ||
export const useSubmit = <T extends FetchCommandInstance, MapperResponse>( | ||
command: T, | ||
{ | ||
disabled = useSubmitDefaultOptions.disabled, | ||
dependencyTracking = useSubmitDefaultOptions.dependencyTracking, | ||
cacheOnMount = useSubmitDefaultOptions.cacheOnMount, | ||
initialData = useSubmitDefaultOptions.initialData, | ||
// debounce = useSubmitDefaultOptions.debounce, | ||
// debounceTime = useSubmitDefaultOptions.debounceTime, | ||
// suspense = useSubmitDefaultOptions.suspense, | ||
// invalidate = useSubmitDefaultOptions.invalidate, | ||
shouldThrow = useSubmitDefaultOptions.shouldThrow, | ||
responseDataModifierFn = useSubmitDefaultOptions.responseDataModifierFn, | ||
}: UseSubmitOptionsType<T, MapperResponse> = useSubmitDefaultOptions, | ||
): UseSubmitReturnType<T, MapperResponse extends never ? ExtractResponse<T> : MapperResponse> => { | ||
const { cacheTime, cacheKey, queueKey } = command; | ||
// const requestDebounce = useDebounce(debounceTime); | ||
const { cache, submitQueue, commandManager } = command.builder; | ||
const requestKey = getCacheRequestKey(command); | ||
const initCacheState = useRef(getCacheState(cache.get(cacheKey, requestKey), cacheOnMount, cacheTime)); | ||
const initialStale = useRef(isStaleCacheData(cacheTime, initCacheState.current?.timestamp)); | ||
const initState = useRef(initialStale.current ? getUseFetchInitialData<T>(initialData) : initCacheState.current); | ||
const [state, actions, setRenderKey] = useDependentState<T>(cacheKey, requestKey, command.builder, initState.current); | ||
const onRequestCallback = useRef<null | OnRequestCallbackType>(null); | ||
const onSuccessCallback = useRef<null | OnSuccessCallbackType<ExtractResponse<T>>>(null); | ||
const onErrorCallback = useRef<null | OnErrorCallbackType<ExtractError<T>>>(null); | ||
const onFinishedCallback = useRef<null | OnFinishedCallbackType<ExtractFetchReturn<T>>>(null); | ||
const onRequestStartCallback = useRef<null | OnStartCallbackType<T>>(null); | ||
const onResponseStartCallback = useRef<null | OnStartCallbackType<T>>(null); | ||
const onDownloadProgressCallback = useRef<null | OnProgressCallbackType>(null); | ||
const onUploadProgressCallback = useRef<null | OnProgressCallbackType>(null); | ||
const handleSubmit = (...parameters: Parameters<T["send"]>) => { | ||
let request = command; | ||
const options = parameters[0]; | ||
if (options?.data) { | ||
request = request.setData(options.data) as T; | ||
} | ||
if (options?.params) { | ||
request = request.setParams(options.params) as T; | ||
} | ||
if (options?.queryParams) { | ||
request = request.setQueryParams(options.queryParams) as T; | ||
} | ||
if (!disabled) { | ||
submitQueue.add(request); | ||
} | ||
}; | ||
const handleCallbacks = (response: ExtractFetchReturn<T> | undefined) => { | ||
if (response) { | ||
if (response[0]) { | ||
onSuccessCallback?.current?.(response[0]); | ||
} | ||
if (response[1]) { | ||
onErrorCallback?.current?.(response[1]); | ||
if (shouldThrow) { | ||
throw { | ||
message: "Fetching Error.", | ||
error: response[1], | ||
}; | ||
} | ||
} | ||
onFinishedCallback?.current?.(response); | ||
} | ||
}; | ||
const handleGetUpdatedCache = (cacheData: CacheValueType<ExtractResponse<T>, ExtractError<T>>) => { | ||
actions.setCacheData(cacheData, false); | ||
handleCallbacks(cacheData.response); | ||
}; | ||
const handleGetRefreshedCache = () => { | ||
actions.setRefreshed(true, false); | ||
actions.setTimestamp(new Date(), false); | ||
handleCallbacks([state.data, state.error, state.status]); | ||
}; | ||
const handleGetLoadingEvent = ({ isLoading, isRetry }: SubmitLoadingEventType) => { | ||
actions.setLoading(isLoading, false); | ||
onRequestCallback.current?.({ isRetry }); | ||
}; | ||
const handleDownloadProgress = (progress: FetchProgressType) => { | ||
onDownloadProgressCallback?.current?.(progress); | ||
}; | ||
const handleUploadProgress = (progress: FetchProgressType) => { | ||
onUploadProgressCallback?.current?.(progress); | ||
}; | ||
const handleRequestStart = (middleware: T) => { | ||
onRequestStartCallback?.current?.(middleware); | ||
}; | ||
const handleResponseStart = (middleware: T) => { | ||
onRequestStartCallback?.current?.(middleware); | ||
}; | ||
const handleMountEvents = () => { | ||
const downloadUnmount = commandManager.events.onDownloadProgress(queueKey, handleDownloadProgress); | ||
const uploadUnmount = commandManager.events.onUploadProgress(queueKey, handleUploadProgress); | ||
const requestStartUnmount = commandManager.events.onRequestStart(queueKey, handleRequestStart); | ||
const responseStartUnmount = commandManager.events.onResponseStart(queueKey, handleResponseStart); | ||
const loadingUnmount = submitQueue.events.getLoading(queueKey, handleGetLoadingEvent); | ||
const getDataUnmount = cache.events.get<T>(requestKey, handleGetUpdatedCache); | ||
const getRefreshedUnmount = cache.events.getRefreshed(requestKey, handleGetRefreshedCache); | ||
return () => { | ||
downloadUnmount(); | ||
uploadUnmount(); | ||
requestStartUnmount(); | ||
responseStartUnmount(); | ||
loadingUnmount(); | ||
getDataUnmount(); | ||
getRefreshedUnmount(); | ||
}; | ||
}; | ||
const handleData = () => { | ||
return responseDataModifierFn && state.data ? responseDataModifierFn(state.data) : state.data; | ||
}; | ||
const handleDependencyTracking = () => { | ||
if (!dependencyTracking) { | ||
Object.keys(state).forEach((key) => setRenderKey(key as Parameters<typeof setRenderKey>[0])); | ||
} | ||
}; | ||
/** | ||
* Initialization of the events related to data exchange with cache and queue | ||
* This allow to share the state with other hooks and keep it related | ||
*/ | ||
useDidMount(() => { | ||
handleDependencyTracking(); | ||
return handleMountEvents(); | ||
}); | ||
return { | ||
submit: handleSubmit, | ||
get data() { | ||
setRenderKey("data"); | ||
return handleData() as (MapperResponse extends never ? ExtractResponse<T> : MapperResponse) extends never | ||
? ExtractResponse<T> | ||
: MapperResponse extends never | ||
? ExtractResponse<T> | ||
: MapperResponse; | ||
}, | ||
get error() { | ||
setRenderKey("error"); | ||
return state.error; | ||
}, | ||
get isSubmitting() { | ||
setRenderKey("loading"); | ||
return state.loading; | ||
}, | ||
get status() { | ||
setRenderKey("status"); | ||
return state.status; | ||
}, | ||
get retryError() { | ||
setRenderKey("retryError"); | ||
return state.retryError; | ||
}, | ||
get retries() { | ||
setRenderKey("retries"); | ||
return state.retries; | ||
}, | ||
get timestamp() { | ||
setRenderKey("timestamp"); | ||
return state.timestamp; | ||
}, | ||
get isOnline() { | ||
setRenderKey("isOnline"); | ||
return state.isOnline; | ||
}, | ||
get isFocused() { | ||
setRenderKey("isFocused"); | ||
return state.isFocused; | ||
}, | ||
get isStale() { | ||
return isStaleCacheData(cacheTime, state.timestamp); | ||
}, | ||
actions, | ||
isDebouncing: false, | ||
isRefreshed: false, | ||
onRequest: (callback: OnRequestCallbackType) => { | ||
onRequestCallback.current = callback; | ||
}, | ||
onSuccess: (callback: OnSuccessCallbackType<ExtractResponse<T>>) => { | ||
onSuccessCallback.current = callback; | ||
}, | ||
onError: (callback: OnErrorCallbackType<ExtractError<T>>) => { | ||
onErrorCallback.current = callback; | ||
}, | ||
onFinished: (callback: OnFinishedCallbackType<ExtractFetchReturn<T>>) => { | ||
onFinishedCallback.current = callback; | ||
}, | ||
onRequestStart: (callback: OnStartCallbackType<T>) => { | ||
onRequestStartCallback.current = callback; | ||
}, | ||
onResponseStart: (callback: OnStartCallbackType<T>) => { | ||
onResponseStartCallback.current = callback; | ||
}, | ||
onDownloadProgress: (callback: OnProgressCallbackType) => { | ||
onDownloadProgressCallback.current = callback; | ||
}, | ||
onUploadProgress: (callback: OnProgressCallbackType) => { | ||
onUploadProgressCallback.current = callback; | ||
}, | ||
}; | ||
}; |
import { | ||
FetchMethodType, | ||
FetchProgressType, | ||
SubmitLoadingEventType, | ||
CacheValueType, | ||
ExtractError, | ||
ExtractResponse, | ||
FetchCommandInstance, | ||
ExtractFetchReturn, | ||
ExtractResponse, | ||
ExtractError, | ||
ExtractRequest, | ||
ExtractEndpoint, | ||
ExtractHasData, | ||
ExtractHasParams, | ||
ExtractHasQueryParams, | ||
CacheValueType, | ||
ClientResponseType, | ||
} from "@better-typed/hyper-fetch"; | ||
import { UseDependentStateActions, UseDependentStateType } from "../use-dependent-state/use-dependent-state.types"; | ||
import { UseDependentStateType, UseDependentStateActions } from "../use-dependent-state/use-dependent-state.types"; | ||
export type UseSubmitOptionsType<T extends FetchCommandInstance, MapperResponse> = { | ||
disabled?: boolean; | ||
queueKey: string; | ||
invalidate: (string | FetchCommandInstance)[]; | ||
dependencies?: any[]; | ||
retry?: boolean | number; | ||
retryTime?: number; | ||
cacheTime?: number; | ||
cacheKey?: string; | ||
cacheOnMount?: boolean; | ||
initialCacheData?: ExtractFetchReturn<T> | null; | ||
initialData?: CacheValueType<ExtractResponse<T>, ExtractError<T>> | null; | ||
initialData?: CacheValueType<ExtractResponse<T>, ExtractError<T>>["response"] | null; | ||
debounce?: boolean; | ||
@@ -33,11 +22,4 @@ debounceTime?: number; | ||
shouldThrow?: boolean; | ||
cancelable?: boolean; | ||
offline?: boolean; | ||
mapperFn?: ((data: ExtractResponse<T>) => MapperResponse) | null; | ||
deepCompareFn?: | ||
| (( | ||
previousValues: ClientResponseType<ExtractResponse<T>, ExtractError<T>>, | ||
newValues: ClientResponseType<ExtractResponse<T>, ExtractError<T>>, | ||
) => boolean) | ||
| null; | ||
responseDataModifierFn?: ((data: ExtractResponse<T>) => MapperResponse) | null; | ||
dependencyTracking?: boolean; | ||
}; | ||
@@ -47,27 +29,25 @@ | ||
UseDependentStateType<ExtractResponse<T>, ExtractError<T>>, | ||
"data" | ||
"data" | "refreshError" | "loading" | ||
> & { | ||
data: null | (MapperResponse extends never ? ExtractResponse<T> : MapperResponse); | ||
actions: UseDependentStateActions<ExtractResponse<T>, ExtractError<T>>; | ||
onRequest: (callback: OnRequestCallbackType) => void; | ||
onSuccess: (callback: OnSuccessCallbackType<ExtractResponse<T>>) => void; | ||
onError: (callback: OnErrorCallbackType<ExtractError<T>>) => void; | ||
onFinished: (callback: OnFinishedCallbackType<ExtractFetchReturn<T>>) => void; | ||
isRefreshed: boolean; | ||
isRefreshingError: boolean; | ||
onRequestStart: (callback: OnStartCallbackType<T>) => void; | ||
onResponseStart: (callback: OnStartCallbackType<T>) => void; | ||
onDownloadProgress: (callback: OnProgressCallbackType) => void; | ||
onUploadProgress: (callback: OnProgressCallbackType) => void; | ||
isSubmitting: boolean; | ||
isStale: boolean; | ||
isDebouncing: boolean; | ||
refresh: () => void; | ||
submit: FetchMethodType< | ||
MapperResponse extends never ? ExtractResponse<T> : MapperResponse, | ||
ExtractRequest<T>, | ||
any, | ||
ExtractError<T>, | ||
ExtractEndpoint<T>, | ||
ExtractHasData<T>, | ||
ExtractHasParams<T>, | ||
ExtractHasQueryParams<T> | ||
>; | ||
submit: () => void; | ||
}; | ||
export type OnRequestCallbackType = (options: Omit<SubmitLoadingEventType, "isLoading">) => void; | ||
export type OnSuccessCallbackType<DataType> = (data: DataType) => void; | ||
export type OnErrorCallbackType<ErrorType> = (error: ErrorType) => void; | ||
export type OnFinishedCallbackType<ResponseType> = (response: ResponseType) => void; | ||
export type OnStartCallbackType<T extends FetchCommandInstance> = (middleware: T) => void; | ||
export type OnProgressCallbackType = (progress: FetchProgressType) => void; |
{ | ||
"name": "@better-typed/react-hyper-fetch", | ||
"version": "1.0.0-beta.1", | ||
"version": "1.0.0-beta.2", | ||
"private": false, | ||
@@ -5,0 +5,0 @@ "description": "React hooks and utils for the hyper-fetch", |
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
58801
1129
0