【发布时间】:2020-06-19 07:05:30
【问题描述】:
我使用 @apollo/react-hooks 每 500 万次从 GraphQL 查询中轮询一次数据。
我的查询接受包括当前日期时间的参数列表,如下所示:
const MyComponent = ({ query }) => {
const {loading, error, data} = useQuery(query, {
variables: {
variable1: valVariable1,
variable2: valVariable2,
variable3: valVariable3,
currentLocalDateTime: getCurrentLocalDateTime(),
},
pollInterval: 300000
});
if (loading) {
return <h1>Loading...</h1>;
};
if (error) {
return <h1>Error! {JSON.stringify(error)}</h1>;
}
return <div> Data: {JSON.stringify(data)}</div>;
});
假设我在“2020-03-06 08h:00mn”调用我的第一个查询,使用上面定义的 pollInterval,我的第二个查询将在 08h:05mn 调用,第三个查询将在 08h 调用:1000万"
预期行为
当我在 1200 万之后查看 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()更新我的变量,然后像这样再次调用查询:
const MyComponent = ({ query }) => {
const [getMyData, { loading, data }] = useLazyQuery(query);
if (loading) {
return <h1>Loading...</h1>;
};
if (error) {
return <h1>Error! {JSON.stringify(error)}</h1>;
}
// Remove the previous created interval then:
setInterval(() => {
const newVariables = {...variables};
newVariables['currentLocalDateTime'] = getCurrentLocalDateTime();
getMyData({variables: newVariables});
}, 300000);
return <div> Data: {JSON.stringify(data)}</div>;
}
但似乎我正在以“肮脏的方式”使用 setInterval 重新实现默认的 Apollo 轮询。所以我不确定这是否是一个解决方案。
有更新 React Apollo 轮询变量的反馈或经验吗?
【问题讨论】:
标签: reactjs react-hooks react-apollo-hooks