Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-query: Show loading spinner while fetching data

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>

like image 848
Kuzyo Yaroslav Avatar asked Dec 13 '22 08:12

Kuzyo Yaroslav


1 Answers

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

like image 142
rphlmr Avatar answered Dec 22 '22 23:12

rphlmr