TanStackT
TanStack6mo ago
74 replies
sacred-rose

Reset form after Submit not working as expected?

So, I have a React App and a simple form and I want to set the default values to whatever the form has at the time of submission.
However, doing so resets the form to the original defaultValues, instead of the new ones passed to the function.

Is there anything I'm doing wrong?

Here's a snippet with this:

import { Button } from '@/components/ui/button';
import { useAppForm } from '@/hooks/form';
import { useStore } from '@tanstack/react-form';
import { z } from 'zod';

const formSchema2 = z.object({
  gender: z.boolean(),
});

export function TestForm() {
  const form = useAppForm({
    defaultValues: {
        gender: true,
    },
    validators: {
      onChange: formSchema2,
    },
    onSubmit: async (params) => {
      // params.value is correct here. If the toggle is false, it shows params.value.gender is false
      console.log(params.value);

      params.formApi.reset(params.value);
      // after this line, the form goes back to the original defaultValues ({gender: true}) instead of the new one ({gender:false})
    },
  });

  return (
    <div>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          form.handleSubmit();
        }}
      >
        <form.AppForm>
          <form.AppField
            name='gender'
            children={(field) => <field.ToggleField name={field.name} label='Show on Resume' className='ml-2' />}
          />
          <Button type='button' onClick={() => form.handleSubmit()} disabled={!isDirty} className='mt-4'>
            Submit
          </Button>
        </form.AppForm>
      </form>
    </div>
  );
}
Was this page helpful?