usePrefetchQuery + useQuery for Form Validation
I have a Form where the user inputs an address.
Once the Address is entered (Street, Postal Code, City) I fire use usePrefetchQuery to check against a backend if the entered data is a know address
When the user submits the form I need to display a option to the user if there where multiple matching locations for the entered data.
How would I do that?
The benefits in using
usePrefetchQuery
would be that the user would not have to wait for the request once the form is submitted as there's more fields (after the address) for them to fill before they hit submit.4 Replies
dependent-tan•12mo ago
you can't call hooks in event handlers, so I'm not really sure what you're trying to do ...
xenial-blackOP•12mo ago
Okay so this is my Form:
Once the user filled the address-input-fields I have all the data i need to verify the address.
I have an onBlur event where I make some checks and eventually trigger the prefetchQuery.
Now my validated addresses are cached - that's great! 💪
Even when the user edits the location inputs, they are getting cached again. 💪
Switching the input back to an already cached address? That's covered 💪
Now when the form is submitted I want to know if the entered address is valid - either from the cached data or if the address was changed just before hitting submit - wait for the request to finish first.
What I would do without react query would probably be:
dependent-tan•12mo ago
await queryClient.fetchQuery
xenial-blackOP•12mo ago
That works perfectly - thank you!
I had some weird issue where it returned the
queryKey, queryFn, staleTime and enabled
- but i can't reproduce it anymore now 🫠