UNPKG

react-accio

Version:

Declaratively fetch multiple APIs with a single React component.

3 lines (2 loc) 5.29 kB
import{createElement as t,Component as e,forwardRef as r,createContext as o}from"react";import n from"hoist-non-react-statics";function i(t){return t.then(function(t){return[null,t]}).catch(function(t){return[t]})}function s(t,e){return i(fetch(t,e)).then(function(t){var e=t[0],r=t[1];if(e)throw new Error("Accio error: "+e.message);if(!1===r.ok)throw new Error("Accio failed to fetch: "+r.url+" "+r.status+" ("+r.statusText+")");return i(r.json())}).then(function(t){var e=t[0],r=t[1];if(e)throw new Error("Error parsing response to json: "+e.message);return r})}var c,p,a={resolver:s,method:"GET"},u={};function h(t,e){var r=t;return e.body&&(r+=JSON.stringify(e.body)),r}Object.defineProperties(u,{resolver:(c=a,p="resolver",{get:function(){return c[p]},set:function(t){if("function"!=typeof t)throw new TypeError("Expected resolver to be a function. But instead got "+typeof t+". Check your "+p+" assignment to Accio defaults.");c[p]=t}}),method:{get:function(){return a.method},set:function(t){if(!["GET","POST"].includes(t))throw new TypeError("Invalid method "+t+". Only GET & POST are supported. Check your method assignment to Accio defaults.");a.method=t}}});var f=o(null),l=f.Provider,d=f.Consumer,y=function(e){function r(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];e.apply(this,t),this.cache=function(t){if("memory"===t)return new Map;if("localStorage"===t)throw new Error("Local storage cache support is incomplete. Please use memory in the meantime.");throw new Error("Unknown AccioCache storage type :/")}(this.props.use)}return e&&(r.__proto__=e),(r.prototype=Object.create(e&&e.prototype)).constructor=r,r.prototype.render=function(){return t(l,{value:this.cache},this.props.children)},r}(e);y.defaultProps={use:"memory"};var m=d,v=new Set(["children","url","context","defer","ignoreCache","onComplete","onError","onShowLoading","onStartFetching","timeout","_cache"]);function g(t){for(var e={},r=Object.keys(t),o=0;o<r.length;o++){var n=r[o];v.has(n)||(e[n]=t[n])}return e}var E={PRELOAD_ERROR:-1,IDLE:0,PRELOADING:1,PRELOADED:2},w=function(t){function e(){for(var e=[],r=arguments.length;r--;)e[r]=arguments[r];t.apply(this,e),this.state={loading:!1,response:null,error:null,trigger:this.doWork.bind(this)},this.preloadStatus=E.IDLE,this.preloadError=null,this.requestId=0}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.preload=function(){var t=this;return Promise.resolve().then(function(){if(t.props._cache)return t.preloadStatus<E.PRELOADING?(t.preloadStatus=E.PRELOADING,i(t.doFetch.call(t)).then(function(e){var r=e[0],o=e[1];return r?(t.preloadStatus=E.PRELOAD_ERROR,void(t.preloadError=r)):(t.preloadStatus=E.PRELOADED,o)})):void 0;console.warn("Preloading without cache is not supported. This can be fixed by wrapping your app with <AccioCacheProvider />.")})},e.prototype.componentDidMount=function(){!0!==this.props.defer&&this.doWork.call(this)},e.prototype.componentWillUnmount=function(){this.timer&&clearTimeout(this.timer)},e.prototype.componentDidUpdate=function(t){var e=this.props.fetchKey;e&&e(this.props)!==e(t)&&this.doWork.call(this)},e.prototype.doWork=function(){var t=this,e=++this.requestId,r=this.props,o=r._cache,n=r.onStartFetching,s=r.timeout,c=h(r.url,g(this.props));if(!o||this.preloadStatus!==E.PRELOADED)return"number"==typeof s?this.timer=setTimeout(this.setLoading.bind(this,!0),s):this.setLoading.call(this,!0),"function"==typeof n&&n(),i(this.doFetch.call(this)).then(function(r){var o=r[0],n=r[1];e===t.requestId&&(o&&t.setError.call(t,o),t.timer&&clearTimeout(t.timer),t.setLoading.call(t,!1),t.setResponse.call(t,n))});var p=o.get(c);this.setResponse.call(this,p)},e.prototype.doFetch=function(){var t=this.props,r=t._cache,o=t.context,n=t.ignoreCache,i=t.url,s=e.defaults.resolver,c=g(this.props),p=function(){return s(i,c,o)};if(r&&!1===n){var a=h(i,c);if(r.has(a))return Promise.resolve(r.get(a));var u=p();return r.set(a,u),u.then(function(t){return r.set(a,t),t}).catch(function(t){throw r.delete(a),t})}return p()},e.prototype.setLoading=function(t){"function"==typeof this.props.onShowLoading&&this.props.onShowLoading(),this.setState({loading:t})},e.prototype.setResponse=function(t){"function"==typeof this.props.onComplete&&this.props.onComplete(t),this.setState({response:t})},e.prototype.setError=function(t){"function"==typeof this.props.onError&&this.props.onError(t),this.setState({error:t})},e.prototype.render=function(){return this.props.children(this.state)},e}(e);w.defaults=u,w.defaultProps={defer:!1,ignoreCache:!1,context:{},method:w.defaults.method};var O=function(e){function r(){e.apply(this,arguments)}return e&&(r.__proto__=e),(r.prototype=Object.create(e&&e.prototype)).constructor=r,r.prototype.renderChild=function(e){var r=this.props,o=r.children,n=r.forwardedRef,i=function(t,e){var r={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&-1===e.indexOf(o)&&(r[o]=t[o]);return r}(r,["children","forwardedRef"]);return t(w,Object.assign({},i,{ref:n,_cache:e}),o)},r.prototype.render=function(){return t(m,null,this.renderChild.bind(this))},r}(e),R=r(function(e,r){return t(O,Object.assign({},e,{forwardedRef:r}))});n(R,w);export{R as Accio,s as defaultResolver,y as AccioCacheProvider}; //# sourceMappingURL=index.esm.js.map