Reactjs 如何更新Apollo轮询中的变量?
我正在使用Reactjs 如何更新Apollo轮询中的变量?,reactjs,react-hooks,react-apollo-hooks,Reactjs,React Hooks,React Apollo Hooks,我正在使用@apollo/react hooks从GraphQL查询中每隔5分钟轮询一次数据 我的查询接受一系列参数,包括当前日期和时间,如下所示: constmycomponent=({query})=>{ const{loading,error,data}=useQuery(查询{ 变量:{ 变量1:阀变量1, 变量2:阀变量2, 变量3:阀变量3, currentLocalDateTime:getCurrentLocalDateTime(), }, 投票间隔:30万 }); 如果(装载){
@apollo/react hooks
从GraphQL查询中每隔5分钟轮询一次数据
我的查询接受一系列参数,包括当前日期和时间,如下所示:
constmycomponent=({query})=>{
const{loading,error,data}=useQuery(查询{
变量:{
变量1:阀变量1,
变量2:阀变量2,
变量3:阀变量3,
currentLocalDateTime:getCurrentLocalDateTime(),
},
投票间隔:30万
});
如果(装载){
返回装载。。。;
};
如果(错误){
返回错误!{JSON.stringify(Error)};
}
返回数据:{JSON.stringify(Data)};
});
假设我在“2020-03-06 08h:00mn”调用我的第一个查询,使用上面定义的pollInterval
,我的第二个查询将在08h:05mn调用,“第三个查询将在08h:10mn调用”
预期行为
当我在12mn之后查看Chrome网络上的查询时,我将看到3个具有不同时间变量值的查询:
- 查询1:variables.currentLocalDateTime==“2020-03-06 08h:00mn”
- 查询2:variables.currentLocalDateTime==“2020-03-06 08h:05mn”
- 查询3:variables.currentLocalDateTime==“2020-03-06 08h:10mn”
- 查询1:variables.currentLocalDateTime==“2020-03-06 08h:00mn”
- 查询2:variables.currentLocalDateTime==“2020-03-06 08h:00mn”
- 查询3:variables.currentLocalDateTime==“2020-03-06 08h:00mn”
- 我试图等待
中的useQuery
事件,然后更新变量,但没有帮助,因为它只会在第一次调用(我猜是在新数据进来时调用,但我不确定)onCompleted
- 我尝试使用
而不是useLazyQuery
,然后使用useQuery
更新我的变量,然后像这样再次调用查询:setInterval()
constmycomponent=({query})=>{
const[getMyData,{loading,data}]=useLazyQuery(查询);
如果(装载){
返回装载。。。;
};
如果(错误){
返回错误!{JSON.stringify(Error)};
}
//删除先前创建的间隔,然后:
设置间隔(()=>{
const newVariables={…variables};
newVariables['currentLocalDateTime']=getCurrentLocalDateTime();
getMyData({variables:newVariables});
}, 300000);
返回数据:{JSON.stringify(Data)};
}
但我似乎在以“肮脏的方式”使用setInterval重新实现默认的Apollo轮询。所以我不确定这是否是一个解决方案
是否有更新React Apollo轮询变量的反馈或经验?问题似乎仍然存在 我发现这个线程,其中一个用户评论说我们可以使用
stopPolling
和startPolling(POLL\u INTERVAL)
来更新查询变量,它对我起到了作用:
这篇文章也很有帮助:
以下是一个例子:
const POLL_INTERVAL = 10_000;
const { refetch, stopPolling, startPolling } = useQuery(
MY_QUERY,
{
fetchPolicy: "network-only",
pollInterval: POLL_INTERVAL,
client
}
);
const onFilterChange = variables => {
stopPolling();
refetch({ ...variables });
startPolling(POLL_INTERVAL);
};