Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  10] [ 2]  / answers: 1 / hits: 26368  / 4 Years ago, thu, june 25, 2020, 12:00:00

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>


More From » reactjs

 Answers
5

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


[#50847] Monday, June 15, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelyn

Total Points: 619
Total Questions: 102
Total Answers: 104

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;