T
TanStack13mo ago
optimistic-gold

useQuery in Field validators

Is there a way to use useQuery in Field validators? I have a Form where the user inputs two dates and I make a Request to the Backend to check if those Dates are on a public holiday or not (which would mean the user needs to select a different Date). To use the Caching from useQuery I would like to define my Query somewhere
function useIsPublicHoliday(date: Date) {
return useQuery({
// …
})
}
function useIsPublicHoliday(date: Date) {
return useQuery({
// …
})
}
and then use it in the validation on the Field
<Field
name={…}
validators={{
onBlur: () => {
// ?? How do get the the public holiday data here ??
}
}}
children={…}
/>
<Field
name={…}
validators={{
onBlur: () => {
// ?? How do get the the public holiday data here ??
}
}}
children={…}
/>
I checked the docs and this example but it only uses Promises in the validators: https://tanstack.com/form/latest/docs/framework/react/examples/query-integration
2 Replies
optimistic-gold
optimistic-gold13mo ago
You'll wanna use useMutation, not useQuery 🙂
optimistic-gold
optimistic-goldOP13mo ago
I got it working with useMutation but I'm not mutating any data. This would still fire a request to the backend for every Date the user inputs: User Inputs Dezember 24th 2024 => request to API => response (okay, no public holiday) User Inputs Dezember 25th 2024 => request to API => response (not okay, public holiday) User Inputs Dezember 24th 2024 => request to API => response (okay, no public holiday) // <-- this should have come from the query cache I'm now using await queryClient.fetchQuery - works great 🙂

Did you find this page helpful?