From 3463f9633821d8fa5055cb33a9e2b5e607a3dc96 Mon Sep 17 00:00:00 2001 From: Isaac Way Date: Tue, 14 Mar 2023 09:23:21 -0500 Subject: [PATCH] fixes issue when passing defaultValues and 'form' prop --- src/__tests__/createSchemaForm.test.tsx | 57 +++++++++++++++++++++++++ src/createSchemaForm.tsx | 11 ++++- 2 files changed, 67 insertions(+), 1 deletion(-) 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..bab4ab9 100644 --- a/src/createSchemaForm.tsx +++ b/src/createSchemaForm.tsx @@ -355,8 +355,17 @@ export function createTsForm< throw new Error(useFormResultValueChangedErrorMesssage()); } const resolver = zodResolver(schema); + const hasSetDefaultValues = useRef(false); + // need to manually reset the form state in case 'defaultValues' and 'form' are passed + if (form && defaultValues && !hasSetDefaultValues.current) { + form.reset(defaultValues); + hasSetDefaultValues.current = true; + } const _form = (() => { - if (form) return form; + if (form) { + return form; + } + const uf = useForm({ resolver, defaultValues,