T
TanStack15mo ago
foreign-sapphire

How do you handle undefined or missing useQuery results with Typescript?

I have this pattern in my components all the time:
const MyComponent = () => {
const { data, isLoading } = useQuery( ... );

if (isLoading) return <div>Loading...</div>

// Here typescript complains about data being possibly undefined
const theThingINeed = data.something;

return ( ... )
}
const MyComponent = () => {
const { data, isLoading } = useQuery( ... );

if (isLoading) return <div>Loading...</div>

// Here typescript complains about data being possibly undefined
const theThingINeed = data.something;

return ( ... )
}
How do you solve this elegantly in all your components?
if (!data) {
return <EmptyState />
}
if (!data) {
return <EmptyState />
}
or
if (!data) {
throw new Error("didn't find your data");
}
if (!data) {
throw new Error("didn't find your data");
}
Most of the time I'm sure the data itself exists, and so if I check that loading is over, then I should have my data defined. Should I still have a fallback all the time somehow or is there something else I'm missing?
5 Replies
fascinating-indigo
fascinating-indigo15mo ago
You must check for error. Then it works
foreign-sapphire
foreign-sapphireOP15mo ago
What do you mean? Which error?
fascinating-indigo
fascinating-indigo15mo ago
if isLoading return foo if isError return bar return data // is now defined
foreign-sapphire
foreign-sapphire15mo ago
Status Checks in React Query
How the wrong status check order can negatively impact user experience
foreign-sapphire
foreign-sapphire15mo ago
React Query and TypeScript
Combine two of the most powerful tools for React Apps to produce great user experience, developer experience and type safety.

Did you find this page helpful?