How can I know the networkStatus of all queries in ApolloClient globally?

牧云@^-^@ 提交于 2020-07-21 07:03:25

问题


I am trying to show preloader when a networkStatus is in-flight.

I know that every query returns its own networkStatus, but in my application there are so many different queries. I want to have a way of handling all the networkStatus for all the queries, globally.

What I'm wanting to know inside my code is the answer for: "Is there any query pending on the network?".


回答1:


Currently, there's no way of doing that, at least not easily/built-in. You could request this as a feature on https://github.com/apollographql/apollo-feature-requests.

Depending on what you are wanting to achieve, using a middleware/afterware on your HttpLink could be sufficient, e.g:

import { ApolloLink } from 'apollo-link';

const middleware = new ApolloLink((operation, forward) => {
  console.log('Starting', operation);

  return forward(operation);
});

const afterware = new ApolloLink((operation, forward) => {
  return forward(operation).map(response => {
    console.log('Completed', operation);

    return response;
  });
});

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: ApolloLink.from([
    middleware,
    afterware,
    new HttpLink({ ... }),
  ]),
});

The middleware will be called before each request, and the afterware, after. You can read more about links at: https://www.apollographql.com/docs/link/.

Alternatively, looking at some of the APIs that Apollo exposes publicly, I was able to make the check on this "unofficial" way:

function queriesInFlight() {
  // client is your ApolloClient instance
  const { queryManager } = client;

  return Object.keys(queryManager.queryStore.getStore()).filter(queryId =>
    queryManager.checkInFlight(queryId),
  );
}


来源:https://stackoverflow.com/questions/58028771/how-can-i-know-the-networkstatus-of-all-queries-in-apolloclient-globally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!