问题
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