TanStackT
TanStack8mo ago
38 replies
uncertain-scarlet

reset form state within dialog without useEffect?

I'm not exactly sure this is a direct issue with this form library, but i've been struggling on this a while, so gonna post:

i have a form inside a dialog. the dialog is pretty standard and tracks it's own open/close state. whenever it closes i would like to have it reset the form, so in the openChange prop i say something like if (closing) form.reset(). for some reason though, this doesn't actually reset the form. i assume it's something to do with the render vs state update cycle?

here's some of the relevant code cut down. is there something obvious going wrong here?

export function CreateExpenseDialog() {
  const create = useCreateExpense();
  const route = SearchRoute.useSearchRoute();
  const form = useForm({
    create: create,
    close: route.close,
    open: route.open,
  });

  return (
    <Dialog
      open={route.view() === "open"}
      onOpenChange={(opening) => {
        if (opening) {
          route.open();
        } else {
          form.api.reset();
          route.close();
        }
      }}
    >
        <form onSubmit={prevented(() => void form.api.handleSubmit())}>
          <form.api.AppField
            name="description"
            children={(field) => (
              <field.TextField
                label="Description"
                inputProps={{
                  placeholder: "enter description",
                }}
              />
            )}
          />
          <form.api.AppForm>
            <form.api.SubmitButton>Submit</form.api.SubmitButton>
            <form.api.CancelButton onClick={route.close}>Cancel</form.api.CancelButton>
            <FieldsErrors
              className="col-span-full min-h-32 "
              metas={Object.values(form.metas)}
            />
          </form.api.AppForm>
        </form>
    </Dialog>
  );
}
Was this page helpful?