Not All Lazy Queries Polling when using Apollo

30 views Asked by At

I am using Apollo to query for multiple items when a user clicks a button. The data on the backend can be populated after some time, so I want to use polling to return the result eventually.

I implement this using a loop through the items and call the query with a poll interval. However, I am only receiving results from latest query executed during the last loop.

How can I run multiple queries with a poll interval simultaneously?

    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    const [loadData, { data }] = useLazyQuery(getData);
    ...
                       for (const [idx, data] of Object.entries(data)) {
                            await loadData({
                                variables: { id: dataId },
                                pollInterval: 3000,
                                notifyOnNetworkStatusChange: true,
                                onCompleted: () => {
                                    console.log('loaded', idx);
                                    void onboardData(idx, dataId ?? '');
                                },
                                onError: (e) => {
                                    console.log('error', idx);
                                },
                            });
                        }

Result when there are 3 data:

error 0
error 1
error 2
error 2
error 2
...

I expect output similar to this:

error 0
error 1
error 2
error 0
error 1
error 2
error 1
error 2
error 0
1

There are 1 answers

0
phry On

With lazy queries, inside of the component you can only ever access the data from the last query you started.

That means, they are never the right tool to trigger multiple queries and wait for their results - while you could kinda make it possible to access results by saving the returned Promise instances, those would only ever return one result and never any updates. Polling would be useless here.

As you are essentially doing something outside the scope of React hooks, you probably should use useApolloClient to get your AC instance and then call client.watchQuery multiple times, which would give you observables and would let you control yourself how long you wanted to subscribe to the individual queries you fired off - including polling.