Skip to content

Commit

Permalink
fixes issue when passing defaultValues and 'form' prop
Browse files Browse the repository at this point in the history
  • Loading branch information
iway1 committed Mar 14, 2023
1 parent 790a81c commit 3463f96
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
57 changes: 57 additions & 0 deletions src/__tests__/createSchemaForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<number>();
const [_, setRerender] = useState(0);
return (
<>
<input
value={value !== undefined ? value + "" : ""}
onChange={(e) => {
const value = parseInt(e.target.value);
if (isNaN(value)) onChange(undefined);
else onChange(value);
}}
placeholder={"input"}
/>
<button type={"button"} onClick={() => setRerender((old) => old + 1)}>
rerender button
</button>
{error?.errorMessage && <span>{error.errorMessage}</span>}
</>
);
}

function Outer() {
const form = useForm<any>();

return (
<Form
onSubmit={mockOnSubmit}
schema={z.object({
number: z.number({ required_error: "req" }),
})}
form={form}
defaultValues={defaultValues}
renderAfter={() => <button>submit</button>}
/>
);
}

const mapping = [[z.number(), Input]] as const;
const Form = createTsForm(mapping);
const defaultValues = {
number: 5,
};

render(<Outer />);

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");
Expand Down
11 changes: 10 additions & 1 deletion src/createSchemaForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 3463f96

Please sign in to comment.