T
TanStack5mo ago
manual-pink

isFetching, isLoading, isPending, isError... how to best structure component? (esp. w/ TS)

There are a lot of convenience booleans (isFetching, isLoading, isPending) returned from useQuery() which signal the state of status. I'm a bit confused which ones to use especially in TS where I want data to be defined (and not <data> | undefined) and handle all states around the async request ("loading", "error", "date"). This is the pattern that makes most sense to me:
function MyComponent() {
const { data, isPending, isError } = useQuery(...);

if (isPending) {
return "Loading...";
}

if (isError) {
return "Error";
}

return (
<div>
// TS strict sees data as defined (not <data> | undefined) due to type narrowing from isPending/isError above
{data}
</div>
)
}
function MyComponent() {
const { data, isPending, isError } = useQuery(...);

if (isPending) {
return "Loading...";
}

if (isError) {
return "Error";
}

return (
<div>
// TS strict sees data as defined (not <data> | undefined) due to type narrowing from isPending/isError above
{data}
</div>
)
}
What patterns do you all typically use?
2 Replies
frequent-plum
frequent-plum5mo ago
Status Checks in React Query
How the wrong status check order can negatively impact user experience
frequent-plum
frequent-plum5mo 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?