From 342ef57f61be8b9ca3edeacd2a97077376e45ccb Mon Sep 17 00:00:00 2001 From: Isaac Way Date: Tue, 14 Mar 2023 16:54:24 -0500 Subject: [PATCH] now supports passing both form and default values --- src/__tests__/createSchemaForm.test.tsx | 57 +++++++++++++++++++++++++ src/createSchemaForm.tsx | 7 +++ 2 files changed, 64 insertions(+) diff --git a/src/__tests__/createSchemaForm.test.tsx b/src/__tests__/createSchemaForm.test.tsx index 38f2ff3..2db2318 100644 --- a/src/__tests__/createSchemaForm.test.tsx +++ b/src/__tests__/createSchemaForm.test.tsx @@ -1059,6 +1059,63 @@ describe("createSchemaForm", () => { expect(screen.queryByText("req")).not.toBeInTheDocument(); expect(mockOnSubmit).toHaveBeenCalledWith({ number: 5 }); }); + it("should be possible to pass 'defaultValues' prop and 'form' prop and apply the default values.", async () => { + const mockOnSubmit = jest.fn(); + function Input() { + const { + field: { onChange, value }, + error, + } = useTsController(); + const [_, setRerender] = useState(0); + return ( + <> + { + const value = parseInt(e.target.value); + if (isNaN(value)) onChange(undefined); + else onChange(value); + }} + placeholder={"input"} + /> + + {error?.errorMessage && {error.errorMessage}} + + ); + } + + function Outer() { + const form = useForm(); + + return ( +
} + /> + ); + } + + const mapping = [[z.number(), Input]] as const; + const Form = createTsForm(mapping); + const defaultValues = { + number: 5, + }; + + render(); + + const button = screen.getByText("submit"); + await userEvent.click(button); + + expect(screen.queryByText("req")).not.toBeInTheDocument(); + expect(mockOnSubmit).toHaveBeenCalledWith({ number: 5 }); + }); it("should render the correct component when a schema created with createSchemaForm is optional", () => { const StringSchema = createUniqueFieldSchema(z.string(), "string"); const NumberSchema = createUniqueFieldSchema(z.number(), "number"); diff --git a/src/createSchemaForm.tsx b/src/createSchemaForm.tsx index 55b3f74..29573a4 100644 --- a/src/createSchemaForm.tsx +++ b/src/createSchemaForm.tsx @@ -4,6 +4,7 @@ import React, { FunctionComponent, ReactNode, RefAttributes, + useEffect, useRef, } from "react"; import { ComponentProps } from "react"; @@ -363,6 +364,12 @@ export function createTsForm< }); return uf; })(); + + useEffect(() => { + if (form && defaultValues) { + form.reset(defaultValues); + } + }, []); const { control, handleSubmit, setError } = _form; const _schema = unwrapEffects(schema); const shape: Record = _schema._def.shape();