react-redux-fetch
Version:
A declarative and customizable way to fetch data for React components and manage that data in the Redux state
189 lines (137 loc) • 7.2 kB
JavaScript
exports.__esModule = true;
var _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; };
var _class, _temp;
var _react = require('react');
var React = _interopRequireWildcard(_react);
var _reactRedux = require('react-redux');
var _reduce = require('lodash/reduce');
var _reduce2 = _interopRequireDefault(_reduce);
var _map = require('lodash/map');
var _map2 = _interopRequireDefault(_map);
var _isEqual = require('lodash/isEqual');
var _isEqual2 = _interopRequireDefault(_isEqual);
var _forEach = require('lodash/forEach');
var _forEach2 = _interopRequireDefault(_forEach);
var _memoizeOne = require('memoize-one');
var _memoizeOne2 = _interopRequireDefault(_memoizeOne);
var _selectors = require('../reducers/selectors');
var _capitalizeFirstLetter = require('../utils/capitalizeFirstLetter');
var _capitalizeFirstLetter2 = _interopRequireDefault(_capitalizeFirstLetter);
var _buildActionsFromMappings = require('../utils/buildActionsFromMappings');
var _buildActionsFromMappings2 = _interopRequireDefault(_buildActionsFromMappings);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var getResourceNames = (0, _memoizeOne2.default)(function (config) {
return (0, _map2.default)(config, function (mapping) {
var resource = (0, _buildActionsFromMappings.ensureResourceIsObject)(mapping);
(0, _buildActionsFromMappings.validateResourceObject)(resource);
return '' + resource.name;
});
});
var ReduxFetch = (_temp = _class = function (_React$Component) {
_inherits(ReduxFetch, _React$Component);
/**
* @param {Function} dispatch Redux dispatch function
* @param {Array} mappings Array of objects with shape:
* {resource: ..., method: ..., request: ...}
* @return {Object} functions for the WrappedComponent e.g.: 'dispatchUserFetch()'
* */
function ReduxFetch(props) {
_classCallCheck(this, ReduxFetch);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
if (typeof props.config === 'function') {
throw new Error("react-redux-fetch with render props doesn't support config as a function. Use an array instead.");
}
_this.state = {
dispatchFunctions: ReduxFetch.actionsFromProps(props.dispatch, props.config)
};
return _this;
}
ReduxFetch.prototype.componentDidMount = function componentDidMount() {
var fetchOnMount = this.props.fetchOnMount;
var dispatchFunctions = this.state.dispatchFunctions;
if (!fetchOnMount) {
return;
}
if (typeof fetchOnMount === 'boolean') {
(0, _forEach2.default)(dispatchFunctions, function (dispatchFn) {
return dispatchFn();
});
return;
}
if (Array.isArray(fetchOnMount)) {
fetchOnMount.forEach(function (resourceName) {
return (0, _forEach2.default)(dispatchFunctions, function (dispatchFn, fnName) {
if (fnName.toLowerCase().includes(resourceName.toLowerCase())) {
dispatchFn();
}
});
});
}
};
ReduxFetch.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
return this.props.children !== nextProps.children || !(0, _isEqual2.default)(this.props.fetchData, nextProps.fetchData);
};
ReduxFetch.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this2 = this;
var onFulfil = this.props.onFulfil;
var onReject = this.props.onReject;
if (onFulfil || onReject) {
(0, _map2.default)(this.props.fetchData, function (repository, key) {
if (prevProps.fetchData[key].pending) {
if (onFulfil && repository.fulfilled) {
onFulfil(key, repository, _this2.state.dispatchFunctions);
}
if (onReject && repository.rejected) {
onReject(key, repository, _this2.state.dispatchFunctions);
}
}
});
}
};
ReduxFetch.prototype.render = function render() {
var _props = this.props,
children = _props.children,
render = _props.render,
fetchData = _props.fetchData;
var dispatchFunctions = this.state.dispatchFunctions;
var cb = render || children;
if (typeof cb !== 'function' && process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line
console.error('Warning: Must specify either a render prop, or a render function as children');
}
return cb(_extends({}, fetchData, dispatchFunctions));
};
return ReduxFetch;
}(React.Component), _class.actionsFromProps = function (dispatch, mappings) {
return (0, _reduce2.default)((0, _buildActionsFromMappings2.default)(mappings), function (actions, actionCreator, key) {
var _Object$assign;
return Object.assign({}, actions, (_Object$assign = {}, _Object$assign[ReduxFetch.getDispatchFunctionName(key)] = function () {
var action = actionCreator.apply(undefined, arguments);
if (action) {
dispatch(action);
}
}, _Object$assign));
}, {});
}, _class.getDispatchFunctionName = function (resourceName) {
return 'dispatch' + (0, _capitalizeFirstLetter2.default)(resourceName);
}, _temp);
// TODO: this can probably be memoized with a custom moization function,
// this should make 'shouldComponentUpdate' obsolete
var getFetchData = function getFetchData(state, config) {
return (0, _reduce2.default)(getResourceNames(config), function (data, resourceName) {
// eslint-disable-next-line no-param-reassign
data[resourceName + 'Fetch'] = (0, _selectors.getPromise)(resourceName).fromState(state) || {};
return data;
}, {});
};
var mapStateToProps = function mapStateToProps(state, props) {
return {
fetchData: getFetchData(state, props.config)
};
};
exports.default = (0, _reactRedux.connect)(mapStateToProps)(ReduxFetch);
;