react-refetch
Version:
A simple, declarative, and composable way to fetch data for React components.
541 lines (438 loc) • 22.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _isPlainObject = _interopRequireDefault(require("../utils/isPlainObject"));
var _shallowEqual = _interopRequireDefault(require("../utils/shallowEqual"));
var _handleResponse = _interopRequireDefault(require("../utils/handleResponse"));
var _buildRequest = _interopRequireDefault(require("../utils/buildRequest"));
var _checkTypes = _interopRequireDefault(require("../utils/checkTypes"));
var _PromiseState = _interopRequireDefault(require("../PromiseState"));
var _hoistNonReactStatics = _interopRequireDefault(require("hoist-non-react-statics"));
var _invariant = _interopRequireDefault(require("invariant"));
var _warning = _interopRequireDefault(require("warning"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
var defaultMapPropsToRequestsToProps = function defaultMapPropsToRequestsToProps() {
return {};
};
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
} // Helps track hot reloading.
var nextVersion = 0;
function connectFactory() {
var defaults = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
function connectImpl(map) {
var deprecatedOptionsArgument = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var finalOptions = options;
if ('withRef' in deprecatedOptionsArgument) {
(0, _warning["default"])(false, 'The options argument is deprecated in favor of `connect.options()`. In a future release, support will be removed.');
finalOptions = Object.assign({}, options, {
withRef: deprecatedOptionsArgument.withRef
});
}
(0, _warning["default"])(!(Function.prototype.isPrototypeOf(defaults.buildRequest) && Function.prototype.isPrototypeOf(defaults.Request)), 'Both buildRequest and Request were provided in `connect.defaults()`. ' + 'However, this custom Request would only be used in the default buildRequest.');
(0, _warning["default"])(options.pure === undefined, '`pure` option is no longer supported');
return connect(map, defaults, finalOptions);
}
connectImpl.defaults = function () {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
(0, _checkTypes["default"])(overrides);
return connectFactory(Object.assign({}, defaults, overrides, {
headers: Object.assign({}, defaults.headers, overrides.headers)
}), options);
};
connectImpl.options = function () {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return connectFactory(defaults, Object.assign({}, options, overrides));
};
return connectImpl;
}
var _default = connectFactory({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
exports["default"] = _default;
var omitChildren = function omitChildren(obj) {
// eslint-disable-next-line no-unused-vars
var children = obj.children,
rest = _objectWithoutProperties(obj, ["children"]);
return rest;
};
function connect(mapPropsToRequestsToProps, defaults, options) {
var finalMapPropsToRequestsToProps = mapPropsToRequestsToProps || defaultMapPropsToRequestsToProps;
var dependsOnProps = finalMapPropsToRequestsToProps.length >= 1;
(0, _warning["default"])(finalMapPropsToRequestsToProps.length < 2, 'Passing context to `mapPropsToRequestsToProps` is no longer supported.');
var topFetch;
var topRequest;
if (typeof window !== 'undefined') {
if (window.fetch) {
topFetch = window.fetch.bind(window);
}
if (window.Request) {
topRequest = window.Request.bind(window);
}
} else if (typeof global !== 'undefined') {
if (global.fetch) {
topFetch = global.fetch.bind(global);
}
if (global.Request) {
topRequest = global.Request.bind(global);
}
} else if (typeof self !== 'undefined') {
if (self.fetch) {
topFetch = self.fetch.bind(self);
}
if (self.Request) {
topRequest = self.Request.bind(self);
}
}
defaults = Object.assign({
buildRequest: _buildRequest["default"],
credentials: 'same-origin',
fetch: topFetch,
force: false,
handleResponse: _handleResponse["default"],
method: 'GET',
redirect: 'follow',
mode: 'cors',
refreshing: false,
refreshInterval: 0,
Request: topRequest
}, defaults);
(0, _checkTypes["default"])(defaults);
options = Object.assign({
withRef: false
}, options); // Helps track hot reloading.
var version = nextVersion++;
function coerceMappings(rawMappings) {
(0, _invariant["default"])((0, _isPlainObject["default"])(rawMappings), '`mapPropsToRequestsToProps` must return an object. Instead received %s.', rawMappings);
var mappings = {};
Object.keys(rawMappings).forEach(function (prop) {
mappings[prop] = coerceMapping(prop, rawMappings[prop]);
});
return mappings;
}
function coerceMapping(prop, mapping, parent) {
if (Function.prototype.isPrototypeOf(mapping)) {
return mapping;
}
if (typeof mapping === 'string') {
mapping = {
url: mapping
};
}
(0, _invariant["default"])((0, _isPlainObject["default"])(mapping), 'Request for `%s` must be either a string or a plain object. Instead received %s', prop, mapping);
(0, _invariant["default"])(mapping.hasOwnProperty('url') || mapping.hasOwnProperty('value'), 'Request object for `%s` must have `url` (or `value`) attribute.', prop);
(0, _invariant["default"])(!(mapping.hasOwnProperty('url') && mapping.hasOwnProperty('value')), 'Request object for `%s` must not have both `url` and `value` attributes.', prop);
(0, _invariant["default"])(!(mapping.hasOwnProperty('value') && typeof mapping.value === 'function' && !mapping.hasOwnProperty('comparison')), 'Request object with functional `value` must also declare `comparison`.', mapping.value, mapping.comparison);
(0, _checkTypes["default"])(mapping);
if (parent) {
mapping.parent = parent.parent || parent;
}
mapping = assignDefaults(mapping, parent);
(0, _invariant["default"])((0, _isPlainObject["default"])(mapping.meta), 'meta for `%s` must be a plain object. Instead received %s', prop, mapping.meta);
mapping.equals = function (that) {
var _this = this;
that = that.parent || that;
if (this.comparison !== undefined) {
return this.comparison === that.comparison;
}
return ['value', 'url', 'method', 'headers', 'body'].every(function (c) {
return (0, _shallowEqual["default"])(_this[c], that[c]);
});
}.bind(mapping);
return mapping;
}
function assignDefaults(mapping, parent) {
var rawHeaders = Object.assign({}, defaults.headers, mapping.headers);
var headers = {};
for (var key in rawHeaders) {
// Discard headers with falsy values
if (rawHeaders.hasOwnProperty(key) && rawHeaders[key]) {
// Get the value now if the header is specified as a function
var headerValue = typeof rawHeaders[key] == 'function' ? rawHeaders[key]() : rawHeaders[key];
headers[key] = headerValue;
}
}
return Object.assign({
meta: {}
}, defaults, parent ? {
fetch: parent.fetch,
buildRequest: parent.buildRequest,
handleResponse: parent.handleResponse,
Request: parent.Request,
comparison: parent.comparison,
then: undefined,
andThen: undefined
} : {}, mapping, {
headers: headers
});
}
return function wrapWithConnect(WrappedComponent) {
var RefetchConnect =
/*#__PURE__*/
function (_Component) {
_inherits(RefetchConnect, _Component);
function RefetchConnect(props) {
var _this2;
_classCallCheck(this, RefetchConnect);
_this2 = _possibleConstructorReturn(this, _getPrototypeOf(RefetchConnect).call(this, props));
_this2.version = version; // To avoid undefined data at mount, pre-populated pending PromiseStates
// TODO: de-dupe with update code
var mappings = finalMapPropsToRequestsToProps(omitChildren(props)) || {};
var initDate = Object.keys(mappings).reduce(function (data, prop) {
var mapping = mappings[prop];
if (Function.prototype.isPrototypeOf(mapping)) {
data[prop] = function () {
_this2.refetchDataFromMappings(mapping.apply(void 0, arguments));
};
} else {
data[prop] = _PromiseState["default"].create(mapping.meta);
}
return data;
}, {});
_this2.state = {
mappings: {},
startedAts: {},
data: initDate,
refreshTimeouts: {}
};
return _this2;
}
_createClass(RefetchConnect, [{
key: "componentDidMount",
value: function componentDidMount() {
this.refetchDataFromProps();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (dependsOnProps && !(0, _shallowEqual["default"])(omitChildren(this.props), omitChildren(prevProps))) {
this.refetchDataFromProps();
}
}
}, {
key: "shouldComponentUpdate",
value: function shouldComponentUpdate(nextProps, nextState) {
return this.state.data !== nextState.data || !(0, _shallowEqual["default"])(this.props, nextProps);
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.clearAllRefreshTimeouts();
this._unmounted = true;
}
}, {
key: "render",
value: function render() {
var ref = options.withRef ? 'wrappedInstance' : null;
return _react["default"].createElement(WrappedComponent, _extends({}, this.state.data, this.props, {
ref: ref
}));
}
}, {
key: "getWrappedInstance",
value: function getWrappedInstance() {
(0, _invariant["default"])(options.withRef, 'To access the wrapped instance, you need to specify { withRef: true } in .options().');
return this.refs.wrappedInstance;
}
}, {
key: "refetchDataFromProps",
value: function refetchDataFromProps() {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;
this.refetchDataFromMappings(finalMapPropsToRequestsToProps(omitChildren(props)) || {});
}
}, {
key: "refetchDataFromMappings",
value: function refetchDataFromMappings(mappings) {
var _this3 = this;
mappings = coerceMappings(mappings);
Object.keys(mappings).forEach(function (prop) {
var mapping = mappings[prop];
if (Function.prototype.isPrototypeOf(mapping)) {
_this3.setAtomicState(prop, new Date(), mapping, function () {
_this3.refetchDataFromMappings(mapping.apply(void 0, arguments));
});
return;
}
if (mapping.force || !mapping.equals(_this3.state.mappings[prop] || {})) {
_this3.refetchDatum(prop, mapping);
}
});
}
}, {
key: "refetchDatum",
value: function refetchDatum(prop, mapping) {
var startedAt = new Date();
if (this.state.refreshTimeouts[prop]) {
window.clearTimeout(this.state.refreshTimeouts[prop]);
}
return this.createPromise(prop, mapping, startedAt);
}
}, {
key: "createPromise",
value: function createPromise(prop, mapping, startedAt) {
var _this4 = this;
var meta = mapping.meta;
var initPS = this.createInitialPromiseState(prop, mapping);
var onFulfillment = this.createPromiseStateOnFulfillment(prop, mapping, startedAt);
var onRejection = this.createPromiseStateOnRejection(prop, mapping, startedAt);
if (mapping.hasOwnProperty('value')) {
var value = mapping.value;
if (typeof value === 'function') {
value = value();
}
if (value && typeof value.then === 'function') {
this.setAtomicState(prop, startedAt, mapping, initPS(meta));
return value.then(onFulfillment(meta), onRejection(meta));
} else {
return onFulfillment(meta)(value);
}
} else {
var request = mapping.buildRequest(mapping);
meta.request = request;
this.setAtomicState(prop, startedAt, mapping, initPS(meta));
var fetched = mapping.fetch(request);
return fetched.then(function (response) {
meta.response = response;
meta.component = _this4.refs.wrappedInstance;
return response;
}).then(mapping.handleResponse).then(onFulfillment(meta), onRejection(meta));
}
}
}, {
key: "createInitialPromiseState",
value: function createInitialPromiseState(prop, mapping) {
var _this5 = this;
return function (meta) {
if (typeof mapping.refreshing == 'function') {
var current = _this5.state.data[prop];
if (current) {
current.value = mapping.refreshing(current.value);
}
return _PromiseState["default"].refresh(current, meta);
} else if (mapping.refreshing) {
return _PromiseState["default"].refresh(_this5.state.data[prop], meta);
} else {
return _PromiseState["default"].create(meta);
}
};
}
}, {
key: "createPromiseStateOnFulfillment",
value: function createPromiseStateOnFulfillment(prop, mapping, startedAt) {
var _this6 = this;
return function (meta) {
return function (value) {
var refreshTimeout = null;
if (mapping.refreshInterval > 0 && !_this6._unmounted && _this6.state.mappings[prop] === mapping) {
refreshTimeout = window.setTimeout(function () {
_this6.refetchDatum(prop, Object.assign({}, mapping, {
refreshing: true,
force: true
}));
}, mapping.refreshInterval);
}
if (mapping.then) {
var thenMapping = mapping.then(value, meta);
if (typeof thenMapping !== 'undefined') {
_this6.refetchDatum(prop, coerceMapping(null, thenMapping, mapping));
return;
}
}
_this6.setAtomicState(prop, startedAt, mapping, _PromiseState["default"].resolve(value, meta), refreshTimeout, function () {
if (mapping.andThen) {
_this6.refetchDataFromMappings(mapping.andThen(value, meta));
}
});
};
};
}
}, {
key: "createPromiseStateOnRejection",
value: function createPromiseStateOnRejection(prop, mapping, startedAt) {
var _this7 = this;
return function (meta) {
return function (reason) {
if (mapping["catch"]) {
var catchMapping = mapping["catch"](reason, meta);
if (typeof catchMapping !== 'undefined') {
_this7.refetchDatum(prop, coerceMapping(null, catchMapping, mapping));
return;
}
}
_this7.setAtomicState(prop, startedAt, mapping, _PromiseState["default"].reject(reason, meta), null, function () {
if (mapping.andCatch) {
_this7.refetchDataFromMappings(mapping.andCatch(reason, meta));
}
});
};
};
}
}, {
key: "setAtomicState",
value: function setAtomicState(prop, startedAt, mapping, datum, refreshTimeout, callback) {
if (this._unmounted) {
return;
}
this.setState(function (prevState) {
if (startedAt < prevState.startedAts[prop]) {
return {};
}
return {
startedAts: Object.assign({}, prevState.startedAts, _defineProperty({}, prop, startedAt)),
mappings: Object.assign({}, prevState.mappings, _defineProperty({}, prop, mapping)),
data: Object.assign({}, prevState.data, _defineProperty({}, prop, datum)),
refreshTimeouts: Object.assign({}, prevState.refreshTimeouts, _defineProperty({}, prop, refreshTimeout))
};
}, callback);
}
}, {
key: "clearAllRefreshTimeouts",
value: function clearAllRefreshTimeouts() {
var _this8 = this;
Object.keys(this.state.refreshTimeouts).forEach(function (prop) {
clearTimeout(_this8.state.refreshTimeouts[prop]);
});
}
}]);
return RefetchConnect;
}(_react.Component);
RefetchConnect.displayName = "Refetch.connect(".concat(getDisplayName(WrappedComponent), ")");
RefetchConnect.WrappedComponent = WrappedComponent;
if (process.env.NODE_ENV !== 'production') {
RefetchConnect.prototype.componentDidUpdate = function (previous) {
return function componentDidUpdate() {
if (this.version === version) {
previous.apply(this, arguments);
return;
} // We are hot reloading!
this.version = version;
this.clearAllRefreshTimeouts();
this.refetchDataFromProps();
};
}(RefetchConnect.prototype.componentDidUpdate);
}
return (0, _hoistNonReactStatics["default"])(RefetchConnect, WrappedComponent);
};
}