@shopify/react-form-state
Version:
Manage react forms tersely and type-safe with no magic.
56 lines (55 loc) • 2.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var React = tslib_1.__importStar(require("react"));
var utilities_1 = require("../utilities");
var Nested = /** @class */ (function (_super) {
tslib_1.__extends(Nested, _super);
function Nested() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.changeHandlers = new Map();
_this.handleChange = function (key) {
if (_this.changeHandlers.has(key)) {
return _this.changeHandlers.get(key);
}
var handler = function (newValue) {
var onChange = _this.props.field.onChange;
onChange(function (value) {
var _a;
return tslib_1.__assign({}, value, (_a = {}, _a[key] = typeof newValue === 'function'
? newValue(value[key])
: newValue, _a));
});
};
_this.changeHandlers.set(key, handler);
return handler;
};
return _this;
}
Nested.prototype.shouldComponentUpdate = function (nextProps) {
var _a = nextProps.field, nextValue = _a.value, nextError = _a.error, nextInitialValue = _a.initialValue;
var _b = this.props.field, value = _b.value, error = _b.error, initialValue = _b.initialValue;
return (nextValue !== value ||
nextError !== error ||
nextInitialValue !== initialValue);
};
Nested.prototype.render = function () {
var _this = this;
var _a = this.props, _b = _a.field, name = _b.name, value = _b.value, onBlur = _b.onBlur, initialValue = _b.initialValue, error = _b.error, children = _a.children;
var innerFields = utilities_1.mapObject(value, function (value, fieldPath) {
var initialFieldValue = initialValue[fieldPath];
return {
value: value,
onBlur: onBlur,
name: name + "." + fieldPath,
initialValue: initialFieldValue,
dirty: value !== initialFieldValue,
error: error && error[fieldPath],
onChange: _this.handleChange(fieldPath),
};
});
return children(innerFields);
};
return Nested;
}(React.Component));
exports.default = Nested;