React-query: Show loading spinner while fetching data

Kuzyo Yaroslav picture Kuzyo Yaroslav · Jun 25, 2020 · Viewed 9.2k times · Source

Using react-query in new project and having small issue. Requirement is to show loading spinner on empty page before data is loaded and than after user fetches new results with different query to show spinner above previous results.

First case is pretty easy and well documented:

  const { isLoading, error, data } = useQuery(["list", query], () =>
    fetch(`https://api/list/${query}`)
  );

  if (isLoading) return <p>Loading...</p>;

  return <div>{data.map((item) => <ListItem key={item.id} item={item}/></div>

But, cant figure out second case - because, after query changes react-query doing fetch of new results and data from useQuery is empty as result I get default empty array and in that case falls to that condition - if (isLoading && !data.length )

  const { isLoading, error, data=[] } = useQuery(["list", query], () =>
    fetch(`https://api/list/${query}`)
  );

  if (isLoading && !data.length ) return <p>Loading...</p>;

  return <div>
    {data.map((item) => <ListItem key={item.id} item={item}/>
    {isLoading && <Spinner/>}
  </div>

Answer

rphlmr picture rphlmr · Jun 30, 2020

When you have no cache (first query fetch or after 5 min garbage collector), isLoading switch from true to false (and status === "loading").

But when you already have data in cache and re-fetch (or use query in an other component), useQuery should return previous cached data and re-fetch in background. In that case, isLoading is always false but you have the props "isFetching" that switch from true to false.

In your example, if the variable "query" passed on the array is different between calls, it's normal to have no result. The cache key is build with all variables on the array.

const query = "something"
const { isLoading, error, data } = useQuery(["list",query], () =>
    fetch(`https://api/list/${query}`)
  );

const query = "somethingElse"
const { isLoading, error, data } = useQuery(["list",query], () =>
    fetch(`https://api/list/${query}`)
  );

In that case, cache is not shared because "query" is different on every useQuery