UNPKG

re-use-form

Version:

Easy-to-use React form hooks with built-in validation support

81 lines (67 loc) 3.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = buildPartialHook; var _react = require("react"); var _reducer = require("./reducer"); var _config = require("./config"); 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; } function buildPartialHook(_ref) { var dispatch = _ref.dispatch, formGet = _ref.get, formSet = _ref.set, formGetError = _ref.getError, formInput = _ref.input; return function usePartial(_ref2) { var prefix = _ref2.prefix, config = _objectWithoutProperties(_ref2, ["prefix"]); (0, _react.useEffect)(function () { var validations = config.validations || {}; if (Object.getOwnPropertyNames(validations).length > 0) { config.validations = {}; for (var key in validations) { var path = "".concat(prefix, ".").concat(key); config.validations[path] = validations[key]; if (config.validations[path].partialDeps) { var deps = config.validations[path].deps || []; config.validations[path].deps = deps.concat(config.validations[path].partialDeps.map(function (dep) { return "".concat(prefix, ".").concat(dep); })); } } var resolvedConfig = (0, _config.resolveConfig)(config); dispatch((0, _reducer.addConfig)(resolvedConfig)); return function () { dispatch((0, _reducer.removeConfig)(resolvedConfig)); }; } }, [prefix]); var attrs = formGet(prefix); var get = (0, _react.useCallback)(function (path) { return path ? formGet("".concat(prefix, ".").concat(path)) : formGet(prefix); }, [attrs]); var set = (0, _react.useCallback)(function (pathOrAttrsOrFn, value) { if (typeof pathOrAttrsOrFn === 'string') { return formSet("".concat(prefix, ".").concat(pathOrAttrsOrFn), value); } else { return formSet(pathOrAttrsOrFn, prefix); } }, []); var getError = (0, _react.useCallback)(function (path) { return formGetError("".concat(prefix, ".").concat(path)); }, [formGetError]); var input = function input(path, onChange) { return formInput("".concat(prefix, ".").concat(path), onChange); }; return { attrs: attrs, get: get, set: set, getError: getError, input: input, $: input }; }; }