Return undefined if param is not there

In this code cityById could be undefined and I want that this checks this and then weatherData gets undefined. Problem: I can't wrap this in a condition because of React's Hook Rules
const weatherData = api.weather.getWeather.useQuery(
{
coordinates: cityById.coord,
timezone: dayjs.tz.guess(),
lang: locale,
},
{ refetchOnWindowFocus: false, staleTime: 1000 * 60 * 60 /* 1 hour */ },
);
const weatherData = api.weather.getWeather.useQuery(
{
coordinates: cityById.coord,
timezone: dayjs.tz.guess(),
lang: locale,
},
{ refetchOnWindowFocus: false, staleTime: 1000 * 60 * 60 /* 1 hour */ },
);
4 Replies
FleetAdmiralJakob 🗕 🗗 🗙
After some digging I think this is not possible without sending a request to the server so maybe I have to make a feature request
Dani;
Dani;4mo ago
I usually end up using non-null assertion when I have to deal with situations like this
const weatherData = api.weather.getWeather.useQuery(
{
coordinates: cityById!.coord,
// ^ non-null assertion
timezone: dayjs.tz.guess(),
lang: locale,
},
{
enabled: !!cityById,
// ^ disable the query
refetchOnWindowFocus: false,
staleTime: 1000 * 60 * 60 /* 1 hour */
},
);
const weatherData = api.weather.getWeather.useQuery(
{
coordinates: cityById!.coord,
// ^ non-null assertion
timezone: dayjs.tz.guess(),
lang: locale,
},
{
enabled: !!cityById,
// ^ disable the query
refetchOnWindowFocus: false,
staleTime: 1000 * 60 * 60 /* 1 hour */
},
);
FleetAdmiralJakob 🗕 🗗 🗙
OK, weird. I tried this but the query still runs even with the enabled prop but I will try it again
FleetAdmiralJakob 🗕 🗗 🗙
@Dani; KATT sent me this part of the docs so I think I will try them: https://trpc.io/docs/client/react/disabling-queries#typesafe-conditional-queries-using-skiptoken
Disabling Queries | tRPC
To disable queries, you can pass skipToken as the first argument to useQuery or useInfiniteQuery. This will prevent the query from being executed.