How to intialize default values when using with Tanstack Query #513
-
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? |
Beta Was this translation helpful? Give feedback.
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). |
Beta Was this translation helpful? Give feedback.
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).