Setting queryHash with t3 useQuery good practice?
I have the following problem:
I'm fetching data from an external API that expects a time range with a
from
and a to
value.
Because I want to show the user the total amount of posts (let's say for today) I set the following parameters on useQuery: from = getBeginningOfTodayDate()
and to = getNowDate()
Since getNow
obviously changes with every useQuery
call, the queryKey is also different every time.
This in turn causes the useQuery to return undefined which causes the frontend to show the fallback value if the data is undefined. Instead I would like the useQuery to return cached data until fresh data is available to avoid the flickering.
Now, I think I could simply set the queryHash
to some custom value for that specific query, like so:
Is that good practice or can that cause some issues in the future?
Or would it be better to set the queryKey
or queryKeyHashFn
?4 Replies
why not just remove
to
from the queryKey?Good question. I have multiple queries that only differ by
to
.
All in all, I think it makes most sense to simple set a custom query key for each query.
queryKey
is typed so that it only allows the predefined queryKey with the query parameters.
I think what I would prefer to do would be to be able to pass a custom queryKey instead of the predefined ["router.getTotalPosts", { from, to}]
] (changing the router.getTotalPosts
is not possible due to the typing
It just feels wrong to directly set a queryHash. Maybe I could also write a custom queryHashFn 🤔You could do
["router.getTotalPosts", { from, to: 1}]
. I think it's easier to make the to
query param constant instead of making a queryHashFn that would discard it.
Anyway, i guess the problem with definig the queryHash would be in the case you define two or more different endpoints with the same queryHash. Besisdes than that, it would only revalidate based on the revalidate param. If the query is revalidated at 11:59pm, it will not refresh at 00:00am, even with from
changing. I think that my first suggestions achieves what you wantI'm just confused that it is so hard to just set an own query key