满足条件时,如何在 refetchInterval 上停止反应查询 useQuery 运行?
How can I stop a react-query useQuery running on a refetchInterval when a condition is met?
我需要不断获取数据直到满足条件
我可以使用下面的代码片段按时间间隔设置提取,但我不知道如何在需要时停止 fetchData
。这可能吗?
const { status: answersStatus, data: answers } = useQuery(
['fetchData', { context, activity, stage, country }],
fetchData,
{refetchInterval: 2000});
本地状态:
const [refetchInterval, setRefetchInterval] = React.useState(2000)
const { status: answersStatus, data: answers } = useQuery(
['fetchData', { context, activity, stage, country }],
fetchData,
{refetchInterval});
您可以将 refetchInterval
设置为 false
或 0
以将其关闭。如果您想根据响应执行此操作,onSuccess
、onError
或 onSettled
回调可能是最佳位置:
const [refetchInterval, setRefetchInterval] = React.useState(2000)
const { status: answersStatus, data: answers } = useQuery(
['fetchData', { context, activity, stage, country }],
fetchData,
{
refetchInterval,
onError: () => setRefetchInterval(0)
});
最后我利用了 short-circuit evaluation
所以我的决定是
const { data: answers } = useQuery(
isThereSomethingToGet && [`fetchData`, { ...qmfRouteParams, context: appContext }],
fetchData,
{
refetchIntervalInBackground: true,
refetchInterval: DocusignPolling.INTERVAL,
},
);
当 isThereSomethingToGet
为假时,函数不会被调用。
对我来说,它会导致无限循环,直到将函数传递给 refetchInterval
,如下所示:
refetchInterval: data => (checkMyResponseHere(data) ? false : 2000)
P.S。 react-query v.3.38.0
我需要不断获取数据直到满足条件
我可以使用下面的代码片段按时间间隔设置提取,但我不知道如何在需要时停止 fetchData
。这可能吗?
const { status: answersStatus, data: answers } = useQuery(
['fetchData', { context, activity, stage, country }],
fetchData,
{refetchInterval: 2000});
本地状态:
const [refetchInterval, setRefetchInterval] = React.useState(2000)
const { status: answersStatus, data: answers } = useQuery(
['fetchData', { context, activity, stage, country }],
fetchData,
{refetchInterval});
您可以将 refetchInterval
设置为 false
或 0
以将其关闭。如果您想根据响应执行此操作,onSuccess
、onError
或 onSettled
回调可能是最佳位置:
const [refetchInterval, setRefetchInterval] = React.useState(2000)
const { status: answersStatus, data: answers } = useQuery(
['fetchData', { context, activity, stage, country }],
fetchData,
{
refetchInterval,
onError: () => setRefetchInterval(0)
});
最后我利用了 short-circuit evaluation
所以我的决定是
const { data: answers } = useQuery(
isThereSomethingToGet && [`fetchData`, { ...qmfRouteParams, context: appContext }],
fetchData,
{
refetchIntervalInBackground: true,
refetchInterval: DocusignPolling.INTERVAL,
},
);
当 isThereSomethingToGet
为假时,函数不会被调用。
对我来说,它会导致无限循环,直到将函数传递给 refetchInterval
,如下所示:
refetchInterval: data => (checkMyResponseHere(data) ? false : 2000)
P.S。 react-query v.3.38.0