Skip to content

Commit

Permalink
fix(form): store form callbacks to ref [skip ci]
Browse files Browse the repository at this point in the history
  • Loading branch information
Pavel910 committed May 15, 2024
1 parent 4376273 commit e750e80
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions packages/form/src/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,32 @@ import { FormContext } from "./FormContext";
import { FormPresenter } from "./FormPresenter";
import { FormAPI } from "./FormApi";

type Callbacks<T> = Pick<FormProps<T>, "onChange" | "onInvalid">;

function FormInner<T extends GenericFormData = GenericFormData>(
props: FormProps<T>,
ref: React.ForwardedRef<any>
) {
const dataRef = useRef(props.data);
const callbacksRef = useRef<Callbacks<T>>({
onChange: props.onChange,
onInvalid: props.onInvalid
});

const presenter = useMemo(() => {
const presenter = new FormPresenter<T>();
presenter.init({
data: (props.data || {}) as T,
onChange: data => {
if (typeof props.onChange === "function") {
props.onChange(data, formApi);
if (typeof callbacksRef.current.onChange === "function") {
callbacksRef.current.onChange(data, formApi);
}
},
onInvalid: props.onInvalid
onInvalid: (...args) => {
if (typeof callbacksRef.current.onInvalid === "function") {
callbacksRef.current.onInvalid(...args);
}
}
});
return presenter;
}, []);
Expand All @@ -45,6 +55,13 @@ function FormInner<T extends GenericFormData = GenericFormData>(
});
}, [props.onSubmit, props.disabled, props.validateOnFirstSubmit]);

useEffect(() => {
callbacksRef.current = {
onChange: props.onChange,
onInvalid: props.onInvalid
};
}, [props.onChange, props.onInvalid]);

useEffect(() => {
presenter.setInvalidFields(props.invalidFields || {});
}, [props.invalidFields]);
Expand Down

0 comments on commit e750e80

Please sign in to comment.