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:
const queryResult = api.router.getTotalPosts.useQuery(
{
from,
to,
},
{
queryHash: "getTotalPostAmount",
refetchInterval: 60000,
}
);
return queryResult.data?.data;
const queryResult = api.router.getTotalPosts.useQuery(
{
from,
to,
},
{
queryHash: "getTotalPostAmount",
refetchInterval: 60000,
}
);
return queryResult.data?.data;
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
cje
cje•10mo ago
why not just remove to from the queryKey?
Clemens
ClemensOP•10mo ago
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 🤔
Alky
Alky•10mo ago
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 want
Clemens
ClemensOP•10mo ago
I'm just confused that it is so hard to just set an own query key
Want results from more Discord servers?
Add your server