TanStackT
TanStack9mo ago
2 replies
sacred-rose

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>
  )
}


What patterns do you all typically use?
Was this page helpful?