T
TanStack5mo ago
extended-salmon

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.
<div>
<SearchComponent>
<TableComponent>
</div>
<div>
<SearchComponent>
<TableComponent>
</div>
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.
navigate({
to: ".",
search: () => ({query: inputValue})
})
navigate({
to: ".",
search: () => ({query: inputValue})
})
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
const {query} = Route.useSearch()
const {data, isFetching} = useQuery({
queryKey: [query]
})
}
const {query} = Route.useSearch()
const {data, isFetching} = useQuery({
queryKey: [query]
})
}
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
extended-salmon
extended-salmonOP5mo ago
Currently, I am passing the refetch function and the query params into SearchComponent and compare it with the input values like this.
if (
queryParams?.query === queryInputRef.current?.value
) {
refetch();
} else {
navigate({
to: ".",
search: () => ({
query: queryInputRef.current?.value,
}),
});
}
if (
queryParams?.query === queryInputRef.current?.value
) {
refetch();
} else {
navigate({
to: ".",
search: () => ({
query: queryInputRef.current?.value,
}),
});
}
Is there a better way to achieve this?
optimistic-gold
optimistic-gold5mo ago
Do you want to refetch same query on clicking search? And where is query function located?
extended-salmon
extended-salmonOP5mo 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.
optimistic-gold
optimistic-gold5mo 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.
extended-salmon
extended-salmonOP5mo ago
Yes, that's currently what I have been doing. Just wondering if there is a better solution. Thanks.
optimistic-gold
optimistic-gold5mo ago
I don’t see anything wrong with this approach for your use case.

Did you find this page helpful?