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,