英文:
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(
"queryCompanies",
() => companySearchQuery(currentPage, searchTerm, token)
)
Component:
<div>
{(!isLoadingCompanies) && companies?.map((company, index) => (
<h3>{company?.name}</h3>
))}
{isLoadingCompanies && <LoadingDataSpinner/>}
</div>
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论