More robust Tanstack Query "integration" example
Discussed in https://github.com/TanStack/form/discussions/1014
Originally posted by eckmLJE November 12, 2024 Greetings,
The "React Example: Query Integration" example is pretty half-baked for an in-Tanstack "integration". It shows two things that don't seem to be particular to Query:
- You can initialize default form values with the useQuery result
- You can call a mutate function in handle submit
A more robust example might describe a react-query integration that handles:
- Invalidating the query on successful form submission/mutation
- Resetting the form when the query result data updates
React hook form has the values option (separate from defaultValues) that resets the form on update, and Formik has enableReinitialize which does the same. Passing the query result data to these props is a nice integration that allows you to:
- Call mutate function on submit
- Invalidate query on mutate success
- Query result updates, triggering a reset of the form with new default values in a clean state
It's not clear to me what the best way is to accomplish this with Tanstack Form. I understand the onSuccess callback in useQuery has been deprecated in latest, so I assume I shouldn't use that to call reset() on the form.
I'd love to pick up tanstack form as I'm pretty over formik and react hook form and I love the tanstack field components and validation approach. Some actual integration or endorsed approach between tanstack-form and -query would be great.
And forgive me if I'm missing something in the docs that describes this behavior of reinitializing a live form as clean with a fresh query result.
Thanks!
An example of this code (untested) might be:
const {data, refetch} = useQuery(/**/);
const form = useForm({defaultValues: data, onSubmit({formApi, value}) {formApi.reset;refetch(value)}})
<p onClick={form.handleSubmit}/>