T
TanStack3y ago
exotic-emerald

useQuery with onSubmit

How would I use useQuery in a search page? I have a page with some search fields & when user submits this form a search is made. And I would like to useQuery to work with this because it is also possible to change the items found. Currently if I change the items these changes are not shown unless I re-run the search.
2 Replies
plain-purple
plain-purple3y ago
It would be possible to use the enabled option, and then enable it once the user has hit the search button for that query. You'd then have to manage if the search filters have changed and put that boolean back to false, to prep for the next search.
useQuery({
queryKey: ['queryKey', searchFilters],
enabled: hasUserPressedTheSearchButtonAtLeastOnce, // boolean
staleTime: 1000 * 10 // number of ms before the data in cache should be considered stale
// https://tanstack.com/query/v4/docs/react/reference/useQuery
})
useQuery({
queryKey: ['queryKey', searchFilters],
enabled: hasUserPressedTheSearchButtonAtLeastOnce, // boolean
staleTime: 1000 * 10 // number of ms before the data in cache should be considered stale
// https://tanstack.com/query/v4/docs/react/reference/useQuery
})
exotic-emerald
exotic-emeraldOP3y ago
I'll have a go with that, thanks! That pretty much works. The only slight issue is that query could take a few seconds. So if user changes an item and then quickly opens it again it shows old data. Don't know if there's anything I can do, though. Locking the whole thing down wouldn't be good either as user might want to make slight changes to lots of items. This way he can do this without having to wait for the query to run between each item.

Did you find this page helpful?