Repository navigation
How to intialize default values when using with Tanstack Query #513
Answered
by
samuel-morrissey
michaelkremenetsky
asked this question in
General
|
In const { register, handleSubmit, reset } = useForm({
defaultValues: { sharing: defaults },
});
useEffect(() => {
reset({
sharing: defaults,
});
}, [reset, defaults]);Any idea how to go about using Tanstack Fom with Tanstack Query? |
Answered by
samuel-morrissey
May 31, 2024
Replies: 1 comment 1 reply
|
You can pass the data to de default value with a conditional for when the data is undefined. If the form has not been touched yet, when the data comes, the default value of the form will be updated to the data from react-query. const { data } = useQuery({
queryFn: //...
});
const form = useForm({
defaultValues: {
value: data ?? "";
}
};In this exemple, while data is undefined, the empty string will be used. When the data comes, the value received will be used as default instead. However, if the user type anything on your input before the data comes, the field will be touched and de defaultValue will not be updated (I think it's a good behavior). |
1 reply
Answer selected by
crutchcorn
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can pass the data to de default value with a conditional for when the data is undefined. If the form has not been touched yet, when the data comes, the default value of the form will be updated to the data from react-query.
In this exemple, while data is undefined, the empty string will be used. When the data comes, the value received will be used as default instead. However, if the user type anything on your input before the data comes, the field will be touched and de defaultValue will not be updated (I think it's a good behavior).