form icon indicating copy to clipboard operation
form copied to clipboard

Form options are stale after submit

Open shx-riff opened this issue 1 year ago • 3 comments

Describe the bug

I want to disable the submit button after the submission. I compare options.defaultValues and values from the store to determine whether they are equal. However, the next render after submission contains stale options. This happens likely because of the useIsomorphicLayoutEffect that updates the options here. I wonder maybe the formApi.update can be called during the render

Your minimal, reproducible example

https://codesandbox.io/p/sandbox/elated-brahmagupta-sj6mvk

Steps to reproduce

  1. Type "Johny" in the input
  2. Click the submit button
  3. Click the submit button again

Expected behavior

As a user, I expect that the submit button is disabled after the first click, but it becomes disabled only after the second click

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • OS: Windows
  • Browser: Chrome

TanStack Form adapter

react-form

TanStack Form version

v0.39.0

TypeScript version

v4.4.4

Additional context

If the useQuery is replaced with a useState then everything works as expected.

shx-riff avatar Dec 02 '24 12:12 shx-riff

I wonder maybe the formApi.update can be called during the render

Unfortunately not, since it breaks the rules of React and therefore will cause malfunctions with the React compiler.

crutchcorn avatar Dec 28 '24 02:12 crutchcorn

While it's not a fix itself, but a workaround for this specific case, I fixed the issue by calling formApi.reset() in onSubmit, looks legit enough

shx-riff avatar Mar 21 '25 15:03 shx-riff

I would be very interested in this feature. We need a "You have unsaved changes" warning in a rather complex form, and for that, the form's initial state as per formApi.reset serves as a baseline validation.

For what it's worth, we don't have to do the comparison ourselves. I would be happy if we could get some variation of isFieldDirty that respects the initial state. But having access to the initial form state outside of that field meta would also be useful in the long run. I just don't know the inner workings of this library well enough to judge which is easier.

gregorbg avatar Apr 02 '25 05:04 gregorbg