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