UNPKG

worker-fetch-looper

Version:

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

17 lines (14 loc) 2.76 kB
import{useState as t,useRef as n,useEffect as e}from"react";var r=function(){return{sum:function(t,n){return t+n}}},o=function(){return(o=Object.assign||function(t){for(var n,e=1,r=arguments.length;e<r;e++)for(var o in n=arguments[e])Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o]);return t}).apply(this,arguments)},a=function(t){onmessage=function(n){t(n.data)}},i=function(r){var i=r.timeout,u=r.validate,c=r.runnerAction,s=r.cb,l=r.intialState,f=c.type,p=function(e){var r=e.fn,i=e.intialState,u=t(i||null),c=u[0],s=u[1],l=n(null);return{state:c,run:function(t){try{var n=new Worker(URL.createObjectURL(new Blob(["("+a.toString()+")("+r.toString()+")"],{type:"text/javascript"})));l.current=n,l.current.onmessage=function(t){s(o(o({},t.data.res),{_details:t.data._originalResDetails})),l.current&&(l.current.terminate(),l.current=null)},l.current&&l.current.postMessage(t)}catch(t){console.log(t)}}}}({intialState:l,fn:function(t){var n=t.payload,e=t.type,r=n.url,o=n.method,a=n.body,i={method:o,headers:{"Content-Type":"application/json"}};a&&(i.body=JSON.stringify(a)),fetch(r,i).then((function(t){return t.json()})).then((function(t){postMessage({res:t,type:e})})).catch((function(t){console.log(t)}))}}),y=p.state,d=p.run,h=t(0),v=h[0],g=h[1],m=n();return e((function(){return m.current=setTimeout((function(){(null==u?void 0:u.beforeRequest)?u.beforeRequest(c)&&d(c):d(c),g((function(t){return t+1}))}),i),function(){m.current&&clearTimeout(m.current)}}),[JSON.stringify(c.payload),v]),e((function(){if((null==s?void 0:s.onUpdateState)&&s.onUpdateState({res:y,type:f}),null==u?void 0:u.response)try{if(!u.response({res:y,type:f}))throw new Error("Invalid param");(null==s?void 0:s.onSuccess)&&s.onSuccess({res:y,type:f})}catch(t){(null==s?void 0:s.onCatch)&&s.onCatch({err:t,res:y,type:f})}}),[JSON.stringify(y)]),{state:y}}; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */export{i as useFetchLooper,r as useMyHook}; //# sourceMappingURL=react-hooks-typescript-npm-starter.esm.js.map