Handling loading states when tanstack router and query used together
I am using Tanstack Router and Tanstack Query. I have a page (say index) like this.
The route code is excluded for brevity.
In the
SearchComponent
, I have an input and a button. When the button is clicked, the value of the input is put into the url like this.
That works correctly and when clicked, I can see the value in the url. Now, using that value, I want to query some data with tanstack query. So I did this in the component
I can see the data in the devtool, so it works. I want to show the loading on the search button so I use isFetching
to render some icons and disable the search button. However, the problem is I want to be able to trigger the query again and again with the same query input. But since the search params is not changing, the route is not rerendering. So the query is not triggering. How can I achieve it?6 Replies
rival-blackOP•2mo ago
Currently, I am passing the refetch function and the query params into
SearchComponent
and compare it with the input values like this.
Is there a better way to achieve this?provincial-silver•2mo ago
Do you want to refetch same query on clicking search? And where is query function located?
rival-blackOP•2mo ago
Oh, the query fn is defined in useQuery. And yes, I want to refetch same query when I click search.
I left out queryFn to shorten the question, sorry about that.
provincial-silver•2mo ago
Thats all right, I think I didn’t do a good job on my question -> I wanted to know in which component you are calling useQuery. But anyway to ansver your question 🙂 - Seems like onSearch you could check search params and if those match refetch() else update search params.
rival-blackOP•2mo ago
Yes, that's currently what I have been doing. Just wondering if there is a better solution. Thanks.
provincial-silver•2mo ago
I don’t see anything wrong with this approach for your use case.