T
TanStack2y ago
relaxed-coral

Is there a way to avoid union type with undefined for data that is returned by useQuery?

It seems that however I type the return type of queryFn or provide a generic type to useQuery, data will always be T | undefined. From the docs, I read that the value of data defaults to undefined, but I did not really understand what that means. Does it mean exactly what I am asking lol? That there will always be union with undefined?
16 Replies
relaxed-coral
relaxed-coralOP2y ago
after some more research I am guessing it's only normal that this is the case, before the fetching happens, or before checking cache, data will be undefined. Is that what is meant by data defaulting to undefined? curious why it's not null instead...
flat-fuchsia
flat-fuchsia2y ago
null is a valid value to be returned from the queryFn undefined isn't
relaxed-coral
relaxed-coralOP2y ago
yes, I am talking about TypeScript though
relaxed-coral
relaxed-coralOP2y ago
For example
export async function getFreelancerReviews({
queryKey
}: QueryFunctionContext): Promise<IFeedback[]> {
const [_, userId] = queryKey;

const { data } = await api.get('/api/v1/getuserreviews', { params: { user_id: userId } });

return data;
}
export async function getFreelancerReviews({
queryKey
}: QueryFunctionContext): Promise<IFeedback[]> {
const [_, userId] = queryKey;

const { data } = await api.get('/api/v1/getuserreviews', { params: { user_id: userId } });

return data;
}
yet when I hover over data I get this
No description
flat-fuchsia
flat-fuchsia2y ago
you've already answered your own question
relaxed-coral
relaxed-coralOP2y ago
what does it mean in the docs that data Defaults to undefined?
flat-fuchsia
flat-fuchsia2y ago
api.get can take 10 seconds. the component will still render in that time, with status: 'pending' and data: undefined I haen't written every sentence in the docs so i don't know
relaxed-coral
relaxed-coralOP2y ago
any reason why it's not null?
flat-fuchsia
flat-fuchsia2y ago
we're going in circles now
null is a valid value to be returned from the queryFn undefined isn't
relaxed-coral
relaxed-coralOP2y ago
:( I am talking about data: undefined
flat-fuchsia
flat-fuchsia2y ago
yes, you are asking why data isn't null when status is pending
relaxed-coral
relaxed-coralOP2y ago
correct
flat-fuchsia
flat-fuchsia2y ago
and I'm answering with: becaus you could legally return null from your queryFn and then there wouldn't be any way to distinguish the two I could also say: because that's the way it was designed and we like undefined more than null. Is that better ?
relaxed-coral
relaxed-coralOP2y ago
ohhhhhhh now I perfectly understand you couldn't have phrased it better
flat-fuchsia
flat-fuchsia2y ago
wow okay
relaxed-coral
relaxed-coralOP2y ago
apologies for my misunderstanding haha thank you so much!

Did you find this page helpful?