@undermuz/use-form
Version:
React library for build forms
64 lines (63 loc) • 1.72 kB
JavaScript
// src/useForm/useControlledForm.ts
import { useEffect, useRef } from "react";
import { isEqual } from "underscore";
import { useRefBy } from "../utils/common.js";
var useControlledForm = (form, props) => {
const { value, onChange, options } = props;
const valueRef = useRef(value);
const onChangeRef = useRefBy(onChange);
const mountFlag = useRef(false);
useEffect(() => {
if (!value) {
return;
}
if (value === valueRef.current) {
return;
}
if (isEqual(value, valueRef.current)) {
return;
}
if (options == null ? void 0 : options.debug)
console.log("[useForm][Update values from external]", {
external: value,
current: valueRef.current
});
valueRef.current = value;
form.setValues(value);
}, [value]);
useEffect(() => {
if (!mountFlag.current) {
mountFlag.current = true;
return;
}
if (!onChangeRef.current) {
return;
}
if (valueRef.current !== form.values && !isEqual(valueRef.current, form.values)) {
if (options == null ? void 0 : options.debug)
console.log("[useForm][Emit values to external]", {
current: form.values,
external: valueRef.current
});
valueRef.current = form.values;
onChangeRef.current(form.values);
}
}, [form.values]);
useEffect(() => {
if (!value) {
return;
}
if (value === form.store.getState().values) {
return;
}
if (options == null ? void 0 : options.debug)
console.log("[useForm][Set initials values]", {
external: value,
current: form.store.getState().values
});
form.setValues(value);
}, []);
};
export {
useControlledForm
};