2019-08-09 10:26:22 +00:00
|
|
|
import React from "react";
|
2019-06-19 14:40:52 +00:00
|
|
|
|
2019-08-09 11:14:35 +00:00
|
|
|
import useForm, { UseFormResult } from "@saleor/hooks/useForm";
|
|
|
|
|
|
|
|
export interface FormProps<T> {
|
|
|
|
children: (props: UseFormResult<T>) => React.ReactNode;
|
|
|
|
confirmLeave?: boolean;
|
2019-06-19 14:40:52 +00:00
|
|
|
initial?: T;
|
|
|
|
resetOnSubmit?: boolean;
|
2019-08-09 11:14:35 +00:00
|
|
|
onSubmit?: (data: T) => void;
|
2019-06-19 14:40:52 +00:00
|
|
|
}
|
|
|
|
|
2019-08-09 11:14:35 +00:00
|
|
|
function Form<T>(props: FormProps<T>) {
|
2020-02-24 14:14:48 +00:00
|
|
|
const { children, initial, resetOnSubmit, onSubmit } = props;
|
|
|
|
const renderProps = useForm(initial, onSubmit);
|
2019-06-19 14:40:52 +00:00
|
|
|
|
2019-08-09 11:14:35 +00:00
|
|
|
function handleSubmit(event?: React.FormEvent<any>, cb?: () => void) {
|
|
|
|
const { reset, submit } = renderProps;
|
2019-06-19 14:40:52 +00:00
|
|
|
|
|
|
|
if (event) {
|
|
|
|
event.stopPropagation();
|
|
|
|
event.preventDefault();
|
|
|
|
}
|
2019-08-09 11:14:35 +00:00
|
|
|
|
2019-06-19 14:40:52 +00:00
|
|
|
if (cb) {
|
|
|
|
cb();
|
|
|
|
}
|
2019-08-09 11:14:35 +00:00
|
|
|
|
2019-06-19 14:40:52 +00:00
|
|
|
if (resetOnSubmit) {
|
2019-08-09 11:14:35 +00:00
|
|
|
reset();
|
2019-06-19 14:40:52 +00:00
|
|
|
}
|
|
|
|
|
2019-08-09 11:14:35 +00:00
|
|
|
submit();
|
2019-06-19 14:40:52 +00:00
|
|
|
}
|
2019-08-09 11:14:35 +00:00
|
|
|
|
|
|
|
return <form onSubmit={handleSubmit}>{children(renderProps)}</form>;
|
2019-06-19 14:40:52 +00:00
|
|
|
}
|
2019-08-09 11:14:35 +00:00
|
|
|
Form.displayName = "Form";
|
|
|
|
|
|
|
|
export default Form;
|