holen
Version:
Declarative fetch in React
2 lines • 2.84 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("prop-types")):"function"==typeof define&&define.amd?define(["exports","react","prop-types"],t):t(e.holen=e.holen||{},e.React,e.PropTypes)}(this,function(e,t,n){function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function i(e){return Array.isArray&&Array.isArray(e)?e:[].concat(e)}t="default"in t?t.default:t,n="default"in n?n.default:n;var p=function(e){function t(){var n,s,i;o(this,t);for(var p=arguments.length,a=Array(p),c=0;c<p;c++)a[c]=arguments[c];return n=s=r(this,e.call.apply(e,[this].concat(a))),s.state={fetching:!s.props.lazy,response:void 0,data:void 0,error:void 0},s.doFetch=function(e){var t=Object.assign({},s.props,e),n=t.url,o=t.body,r=t.credentials,i=t.headers,p=t.method;s.setState({fetching:!0});var a=function(e,t){s.willUnmount||s.setState({data:t&&t.data?s.props.transformResponse(t.data):void 0,error:e,fetching:!1,response:t},function(){s.props.onResponse(e,t)})};return fetch(n,{body:o,credentials:r,headers:i,method:p}).then(function(e){if(!s.willUnmount){return e[s.props.type].apply(e).then(function(t){return e.data=t,e})}}).then(function(e){return a(void 0,e),e}).catch(function(e){return a(e,void 0),e})},i=n,r(s,i)}return s(t,e),t.prototype.componentDidMount=function(){this.props.lazy||this.doFetch()},t.prototype.componentWillReceiveProps=function(e){var t=this;["url","method","lazy","type","body"].some(function(n){return t.props[n]!==e[n]})&&this.doFetch(e)},t.prototype.componentWillUnmount=function(){this.willUnmount=!0},t.prototype.render=function(){return this.props.children?(this.props.render||i(this.props.children)[0])({fetching:this.state.fetching,response:this.state.response,data:this.state.data,error:this.state.error,fetch:this.doFetch})||null:null},t}(t.Component);p.propTypes={body:n.any,children:n.func,credentials:n.string,headers:n.object,lazy:n.bool,method:n.oneOf(["get","post","put","patch","delete","GET","POST","PUT","PATCH","DELETE"]),onResponse:n.func,url:n.string.isRequired,type:n.oneOf(["json","text","blob"]),transformResponse:n.func},p.defaultProps={method:"get",type:"json",onResponse:function(){},transformResponse:function(e){return e}},e.default=p,Object.defineProperty(e,"__esModule",{value:!0})});
//# sourceMappingURL=holen.umd.js.map