Retrieving query data without passing the whole queryKey
Hi all,
I have a small custom query:
In some components I have no 'params', so I want to retrieve the data like this:
Unfotrunately, I'm getting indefined as a data, because I did not pass the params.
I've found only one dirty trick to fix it - do not pass the 'params' to queryKey array:
const useData = (params?: IParams) => {
return useQuery({
// eslint-disable-next-lone @tanstack/query/exhaustive-deps
queryKey: [queryKey],
queryFn: () => fetchData(params),
enabled: false
})
}
Is that a 'go-to'?
4 Replies
solid-orange•10mo ago
Hi. If you are using params to make a request they should be included inside the key. This ensures that whenever params will change RQ will make a new request to get data. Basically, RQ maps params passed to the fetch function and data. For example let's say you have a paginated endpoint and you send
{page: 1}
as params to get a data slice for page 1
In this example, each data slice lives under its own key, because of the params you've passed to the key. These are 2 different pieces of data, without this behavior data for page 1 would be overwritten by data for page 2 and vice versa because they would live under the same key.
Applying this to your example, if you remove params from the key, the RQ will not react to the change in params, which is not what you want.
You better try to find a way to get the params and pass them to useData.solid-orange•10mo ago
As an alternative you may use
queryClient.getQueriesData(filters)
to get all the queries that start with the same queryKey
. But then you will need to figure somehow out how to filter the exact piece of data you want to get back https://tanstack.com/query/latest/docs/reference/QueryClient/#queryclientgetqueriesdataTanStack | High Quality Open-Source Software for Web Developers
Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.

national-gold•10mo ago
In some components I have no 'params', so I want to retrieve the data like this:the question is why you think you want that, because very likely, you don't want that 🙂 because with that call:
useData()
, which data are you expecting to see? There might be multiple cache entries for different params
....ambitious-aquaOP•10mo ago
I'm retrieving some data when clicking on the table column.
I'm caching this respose, but I don't want tp cache the request params (clicked table column data).