UNPKG

@thejohnfreeman/loadable

Version:
79 lines 3.35 kB
var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; import * as React from 'react'; var Loading = function () { return React.createElement(React.Fragment, null, "Loading..."); }; function elementFromImported(props, imported) { if (imported instanceof Function || imported instanceof React.Component) { var Component = imported; return React.createElement(Component, __assign({}, props)); } if (imported && typeof imported === 'object' && 'default' in imported) { return elementFromImported(props, imported.default); } return imported; } export var loadable = function (_a) { var _b = _a === void 0 ? {} : _a, _c = _b.delay, delay = _c === void 0 ? 200 : _c, _d = _b.Placeholder, Placeholder = _d === void 0 ? Loading : _d; return function (fetchElement) { var Loadable = (function (_super) { __extends(Loadable, _super); function Loadable() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.state = { element: null }; _this.timer = null; return _this; } Loadable.prototype.componentDidMount = function () { var _this = this; fetchElement(this.props).then(function (imported) { var element = elementFromImported(_this.props, imported); _this.clearTimeout(); _this.setState({ element: element }); }); this.timer = setTimeout(function () { if (_this.state.element) { console.error('timer was not cleared when element loaded'); } else { _this.setState({ element: React.createElement(Placeholder, __assign({}, _this.props)) }); } }, delay); }; Loadable.prototype.componentWillUnmount = function () { this.clearTimeout(); }; Loadable.prototype.render = function () { return this.state.element; }; Loadable.prototype.clearTimeout = function () { clearTimeout(this.timer); this.timer = null; }; return Loadable; }(React.Component)); return Loadable; }; }; //# sourceMappingURL=index.js.map