I'm using @apollo/react-hooks
to poll data from a GraphQL query each 5mn.
My query accepts a list of parameters including the current date time like this:
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>;
});
Let's say I call my first query at "2020-03-06 08h:00mn", using the pollInterval
defined above, my 2nd query will be called at 08h:05mn" and the 3rd one will be called at 08h:10mn"
The expected behaviour
When I look on my query on Chrome's Network after 12mn, I'll see 3 queries with different time variable values:
- Query 1 : variables.currentLocalDateTime === "2020-03-06 08h:00mn"
Query 2 : variables.currentLocalDateTime === "2020-03-06 08h:05mn"
Query 3 :variables.currentLocalDateTime === "2020-03-06 08h:10mn"
The current behaviour
- Query 1 : variables.currentLocalDateTime === "2020-03-06 08h:00mn"
- Query 2 : variables.currentLocalDateTime === "2020-03-06 08h:00mn"
- Query 3 : variables.currentLocalDateTime === "2020-03-06 08h:00mn"
What I tried to do
I tried to wait the
onCompleted
event fromuseQuery
and then update variables but it doesn't help because it will be called only the 1st time (and I guess when new data come in but I'm not sure).I tried to use
useLazyQuery
instead ofuseQuery
and then use asetInterval()
to update my variables then call the query again like this:
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>;
}
But it seems like I'm reimplementing the default Apollo polling using a setInterval in a "dirty way". So I'm not sure if it's a solution.
Any feedback or experience to update a React Apollo polling variables ?