UNPKG

worker-fetch-looper

Version:

This is a Fetch looper based on Web Worker and Fetch API

3 lines (2 loc) 2.02 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("react"),e=function(){return(e=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t}).apply(this,arguments)},n=function(t){onmessage=function(e){t(e.data)}};exports.useFetchLooper=function(r){var o=r.timeout,u=r.validate,a=r.runnerAction,s=r.cb,c=r.intialState,i=a.type,l=function(r){var o=r.fn,u=r.intialState,a=t.useState(u||null),s=a[0],c=a[1],i=t.useRef(null);return{state:s,run:function(t){try{var r=new Worker(URL.createObjectURL(new Blob(["("+n.toString()+")("+o.toString()+")"],{type:"text/javascript"})));i.current=r,i.current.onmessage=function(t){c(e(e({},t.data.res),{_details:t.data._originalResDetails})),i.current&&(i.current.terminate(),i.current=null)},i.current&&i.current.postMessage(t)}catch(t){console.log(t)}}}}({intialState:c,fn:function(t){var e=t.payload,n=t.type,r=e.url,o=e.method,u=e.body,a={method:o,headers:{"Content-Type":"application/json"}};u&&(a.body=JSON.stringify(u)),fetch(r,a).then((function(t){return t.json()})).then((function(t){postMessage({res:t,type:n})})).catch((function(t){console.log(t)}))}}),f=l.state,p=l.run,y=t.useState(0),d=y[0],h=y[1],v=t.useRef();return t.useEffect((function(){return v.current=setTimeout((function(){(null==u?void 0:u.beforeRequest)?u.beforeRequest(a)&&p(a):p(a),h((function(t){return t+1}))}),o),function(){v.current&&clearTimeout(v.current)}}),[JSON.stringify(a.payload),d]),t.useEffect((function(){if((null==s?void 0:s.onUpdateState)&&s.onUpdateState({res:f,type:i}),null==u?void 0:u.response)try{if(!u.response({res:f,type:i}))throw new Error("Invalid param");(null==s?void 0:s.onSuccess)&&s.onSuccess({res:f,type:i})}catch(t){(null==s?void 0:s.onCatch)&&s.onCatch({err:t,res:f,type:i})}}),[JSON.stringify(f)]),{state:f}},exports.useMyHook=function(){return{sum:function(t,e){return t+e}}}; //# sourceMappingURL=react-hooks-typescript-npm-starter.cjs.js.map