Clemens
Clemens
TTCTheo's Typesafe Cult
Created by Clemens on 1/29/2024 in #questions
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?
7 replies