简体   繁体   English

React-query:在获取数据时显示加载微调器

[英]React-query: Show loading spinner while fetching data

Using react-query in new project and having small issue.在新项目中使用 react-query 并且有小问题。 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 )但是,无法弄清楚第二种情况 - 因为,在查询更改后,react-query 从 useQuery 获取新结果和数据是空的,因为结果我得到默认的空数组,在这种情况下属于该条件 - 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>

When you have no cache (first query fetch or after 5 min garbage collector), isLoading switch from true to false (and status === "loading").当您没有缓存时(第一次查询获取或 5 分钟垃圾收集器后),isLoading 从 true 切换到 false(并且状态 ===“正在加载”)。

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.但是当您已经在缓存中有数据并重新获取(或在其他组件中使用查询)时,useQuery 应该返回以前缓存的数据并在后台重新获取。 In that case, isLoading is always false but you have the props "isFetching" that switch from true to false.在这种情况下,isLoading 始终为 false,但您拥有从 true 切换为 false 的道具“isFetching”。

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在这种情况下,缓存不会共享,因为每个 useQuery 上的“查询”都不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM