How to run a number of GraphQL requests in parallel.
React-Native + ApolloJS: Requests sequence without await doesn‘t work.
Package info:
"@apollo/client": "^3.6.8",
"apollo-link-logger": "^2.0.0",
"apollo-link-token-refresh": "^0.4.0",
"graphql": "^16.5.0",
"graphql-tag": "^2.11.0",
"react": "17.0.2",
"react-native": "=0.68.0",
I have a request sequence in React.FC (Apollo client is called in the service’s methods).
const loadData = async() => {
await wait(800);
await dataService1.getData1();
await dataService1.getData2();
await dataService1.getData3();
await dataService1.getData4();
await dataService1.getData5();
await dataService2.getData6();
await dataService3.getData7()
setLoading(false);
};
Real names of services and methods were replaced for this example.
It works … but slowly. It takes about 11+ seconds to load.
I’ve tried to remove await in the function above, but after that Apollo doesn’t send all requests, some requests are simply not sent.
Each request calls intercepter in middleware chain (for adding auth Bearer token) so the root cause of that issue can be in httplink which is at the end of middlewares pipe.
// Constructor of ApolloClientService
this.httpLink = createHttpLink({
uri: `https://${this.api}/graphql`,
});
// this.httpLink = new BatchHttpLink({ uri: `https://${this.api}/graphql`});
this.link = split(({ query }) => {
const {
kind,
operation,
}: {
kind: string;
operation?: string;
} = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
}, this.httpLink);
this.defaultOptions = {
watchQuery: {
fetchPolicy: 'no-cache',
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
mutate: {
// errorPolicy: 'all',
},
};
this.client = new ApolloClient<NormalizedCacheObject>({
link: ApolloLink.from([
onError(this.handleError),
setContext(this.interceptRequest),
apolloLogger,
this.httpLink,
]),
cache: new InMemoryCache(),
defaultOptions: this.defaultOptions,
connectToDevTools: false,
queryDeduplication: false,
});
I haven’t found any workable solution yet without using
BatchLink (our server does not support batches, and we don’t have time now for refactoring,
Apollo hooks (useQuery/useMutation) or Apollo react component.
I think that ApolloJS must wait for the last request to complete before it’s ready to send a new one. I hope it’s not the case.
I’m looking for a solution to be able to send a chain of the requests (not a number of GraphQL queries) concurrently/in parallel like in the REST API from Apollo client.