How can I change the isLoading state to true in React Query when a refetch is triggered?

huangapple go评论67阅读模式
英文:

How can I change the isLoading state to true in React Query when a refetch is triggered?

问题

当触发 refetchCompanies 时,我想将 isLoadingCompanies 状态设置为 true,以便此组件将重新渲染。我只想在 isLoadingCompanies 为 true 时渲染组件,而不是在 isFetchingCompanies 为 true 时渲染。

我的对象:

const {
    isLoading: isLoadingCompanies,
    isFetching: isFetchingCompanies,
    data: dataCompanies,
    refetch: refetchCompanies
} = useQuery(
    "queryCompanies",
    () => companySearchQuery(currentPage, searchTerm, token)
)

组件:

<div>
    {(!isLoadingCompanies) && companies?.map((company, index) => (
        <h3>{company?.name}</h3>
    ))}  
    {isLoadingCompanies && <LoadingDataSpinner/>}
</div>
英文:

When refetchCompanies is triggered, I want to set the isLoadingCompanies state to true so this component will re-render. I only want to render the component when isLoadingCompanies is true, and not when isFetchingCompanies is true.

My object:

const {
    isLoading: isLoadingCompanies,
    isFetching: isFetchingCompanies,
    data: dataCompanies,
    refetch: refetchCompanies
} = useQuery(
    &quot;queryCompanies&quot;,
    () =&gt; companySearchQuery(currentPage, searchTerm, token)
)

Component:

&lt;div&gt;
    {(!isLoadingCompanies) &amp;&amp; companies?.map((company, index) =&gt; (
        &lt;h3&gt;{company?.name}&lt;/h3&gt;
    ))}  
    {isLoadingCompanies &amp;&amp; &lt;LoadingDataSpinner/&gt;}
&lt;/div&gt;

答案1

得分: 1

你可以使用 isFetching 值从 useQuery 返回的值来显示背景刷新时的加载符号。这个值无论是第一次获取数据还是重新获取数据,只要有数据获取操作正在进行,它都会为 true。你也可以使用 isRefetching 来仅检查重新获取数据的情况。

英文:

> How can I change the isLoading state to true in React Query when a refetch is triggered?

The simple answer is: you can't. A query will be in loading state if it's fetching and has no data. So, during a refetch, given that you already have data, your query will not be in loading state.

To display a loading spinner for background refetches, you can look at the isFetching value retuned from useQuery, which will be true whenever any fetch is happening, not matter if it's the first fetch or a refetch. You can also use isRefetching to only check for refetches happening.

huangapple
  • 本文由 发表于 2023年3月4日 02:51:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定