import { useState, ReactNode, PropsWithoutRef } from "react" import { Formik, FormikProps } from "formik" import { validateZodSchema } from "blitz" import { z } from "zod" export interface FormProps> extends Omit, "onSubmit"> { /** All your form fields */ children?: ReactNode /** Text to display in the submit button */ submitText?: string schema?: S onSubmit: (values: z.infer) => Promise initialValues?: FormikProps>["initialValues"] } interface OnSubmitResult { FORM_ERROR?: string [prop: string]: any } export const FORM_ERROR = "FORM_ERROR" export function Form>({ children, submitText, schema, initialValues, onSubmit, ...props }: FormProps) { const [formError, setFormError] = useState(null) return ( { const { FORM_ERROR, ...otherErrors } = (await onSubmit(values)) || {} if (FORM_ERROR) { setFormError(FORM_ERROR) } if (Object.keys(otherErrors).length > 0) { setErrors(otherErrors) } }} > {({ handleSubmit, isSubmitting }) => (
{/* Form fields supplied as children are rendered here */} {children} {formError && (
{formError}
)} {submitText && ( )}
)}
) } export default Form