Reset form does not work as expected in combination with `useStore`
Describe the bug
I realize there are some related issues (https://github.com/TanStack/form/issues/1490) but I think there are still some bugs somewhere.
It seems like after resetting to new values, subscribing to the state of those new values reverts them to the default values.
Your minimal, reproducible example
https://stackblitz.com/edit/vitejs-vite-x8aebugd?file=src%2FApp.tsx
Steps to reproduce
- go to sandbox
- observe
x === 1anddate === new Date()in the input fields. this is incorrect. - comment out line 12 and comment in line 13
- observe
x === 5anddate === new Date(2025, 0, 1)in the input fields. this is correct.
Expected behavior
x === 5 and date === new Date(2025, 0, 1)
How often does this bug happen?
Every time
Screenshots or Videos
No response
Platform
- macOS
- brave
- 1.82
TanStack Form adapter
react-form
TanStack Form version
v1.19.5
TypeScript version
No response
Additional context
No response
Can You try form.reset(data, { keepDefaultValues: true })
{ keepDefaultValues: true }. this will set the data as new Default Value
{ keepDefaultValues: true }. this will set the data as new Default Value
I think you meant, this will keep the existing default values.
Regardless, yes, that fixed the problem. I'm not quite sure why modifying the default values or not should influence the end result. It seems to me even if I do replace the default values with the new values, the end state should reflect the values I passed into reset, i.e. x === '5'.
Yeah, Not Sure about that behavior, @LeCarbonator might give us some info on this ?
I believe the main problem is this:
form.reset(values)resets to a new set of values- after the reset occurred, a new render cycle with an update value starts.
- the form options are reevaluated, and it notices that the incoming defaultValues are not the same as the currently saved defaultValues.
- this would usually be ignored because the form is touched, but the reset form now accepts defaultValues again. This is intended to be for async initial values, but it undoes your
form.reset-provided values
@LeCarbonator ok so... it's a bug? sounds like a bug.
This is a problem because setting values from an existing record in the db is a common pattern in my app. Because .reset has unexpected behaviors, I'm using this as a workaround but its not ideal because I have an unneeded copy of the form in state:
const [formFromDb, setFormFromDb] = useState<Form>();
const form = useForm({ defaultValues: formFromDb ?? defaultValues });
useEffect(() => {
if (!dataFromDb) return;
const newForm = toForm(dataFromDb);
form.reset(newForm);
setFormFromDb(newForm);
}, [dataFromDb])
Yeah, it's a bug, but it's one that is really difficult to work around. It needs some time to be properly looked at
This bug is a blocker for me to use this library. I hope the contributors fix it as soon as possible. 🙏