You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

withReducer.js 2.6 KiB

3 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. exports.__esModule = true;
  4. exports.default = void 0;
  5. var _extends3 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
  6. var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
  7. var _react = require("react");
  8. var _setDisplayName = _interopRequireDefault(require("./setDisplayName"));
  9. var _wrapDisplayName = _interopRequireDefault(require("./wrapDisplayName"));
  10. var noop = function noop() {};
  11. var withReducer = function withReducer(stateName, dispatchName, reducer, initialState) {
  12. return function (BaseComponent) {
  13. var factory = (0, _react.createFactory)(BaseComponent);
  14. var WithReducer =
  15. /*#__PURE__*/
  16. function (_Component) {
  17. (0, _inheritsLoose2.default)(WithReducer, _Component);
  18. function WithReducer() {
  19. var _this;
  20. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  21. args[_key] = arguments[_key];
  22. }
  23. _this = _Component.call.apply(_Component, [this].concat(args)) || this;
  24. _this.state = {
  25. stateValue: _this.initializeStateValue()
  26. };
  27. _this.dispatch = function (action, callback) {
  28. if (callback === void 0) {
  29. callback = noop;
  30. }
  31. return _this.setState(function (_ref) {
  32. var stateValue = _ref.stateValue;
  33. return {
  34. stateValue: reducer(stateValue, action)
  35. };
  36. }, function () {
  37. return callback(_this.state.stateValue);
  38. });
  39. };
  40. return _this;
  41. }
  42. var _proto = WithReducer.prototype;
  43. _proto.initializeStateValue = function initializeStateValue() {
  44. if (initialState !== undefined) {
  45. return typeof initialState === 'function' ? initialState(this.props) : initialState;
  46. }
  47. return reducer(undefined, {
  48. type: '@@recompose/INIT'
  49. });
  50. };
  51. _proto.render = function render() {
  52. var _extends2;
  53. return factory((0, _extends3.default)({}, this.props, (_extends2 = {}, _extends2[stateName] = this.state.stateValue, _extends2[dispatchName] = this.dispatch, _extends2)));
  54. };
  55. return WithReducer;
  56. }(_react.Component);
  57. if (process.env.NODE_ENV !== 'production') {
  58. return (0, _setDisplayName.default)((0, _wrapDisplayName.default)(BaseComponent, 'withReducer'))(WithReducer);
  59. }
  60. return WithReducer;
  61. };
  62. };
  63. var _default = withReducer;
  64. exports.default = _default;