Skip to content

Commit

Permalink
fix: resetForm should cast typed schema values closes #4347
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed Jul 6, 2023
1 parent 40ce7a9 commit e9b215a
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/old-peaches-boil.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'vee-validate': patch
---

fix: resetForm should cast typed schema values closes #4347
3 changes: 2 additions & 1 deletion packages/vee-validate/src/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -660,7 +660,8 @@ export function useForm<
* Resets all fields
*/
function resetForm(resetState?: Partial<FormState<TValues>>) {
const newValues = resetState?.values ? resetState.values : originalInitialValues.value;
let newValues = resetState?.values ? resetState.values : originalInitialValues.value;
newValues = isTypedSchema(schema) && isCallable(schema.cast) ? schema.cast(newValues) : newValues;
setInitialValues(newValues);
mutateAllPathState(state => {
state.validated = false;
Expand Down
34 changes: 34 additions & 0 deletions packages/zod/tests/zod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,40 @@ test('uses zod default values for initial values', async () => {
);
});

test('reset form should cast the values', async () => {
const valueSpy = vi.fn();
mountWithHoc({
setup() {
const schema = toTypedSchema(
z.object({
age: z.preprocess(arg => Number(arg), z.number()),
})
);

const { values, resetForm } = useForm({
validationSchema: schema,
});

resetForm({ values: { age: '12' } });
// submit now
valueSpy(values);

return {
schema,
};
},
template: `<div></div>`,
});

await flushPromises();
await expect(valueSpy).toHaveBeenCalledTimes(1);
await expect(valueSpy).toHaveBeenLastCalledWith(
expect.objectContaining({
age: 12,
})
);
});

// #4186
test('default values should not be undefined', async () => {
const initialSpy = vi.fn();
Expand Down

0 comments on commit e9b215a

Please sign in to comment.