Thursday, 10 November 2022

How to fetch fresh results with each request and no-cache strategy in Apollo GraphlQL and Angular?

We have a value that is different everytime it's requested, like a nonce. So we want to get that value freshly with each request. Somehow I can't get it to work with Apollo's Angular client.

My first idea was to use watchQuery with the no-cache strategy:

this.apollo.watchQuery<any>({query: NONCE_QUERY, fetchPolicy: 'no-cache'})
  .valueChanges
  .pipe(first())
  .subscribe(response => console.log(response.data.nonce);

This works fine and I get the result.

But when I use this multiple times, like:

this.apollo.watchQuery<any>({query: NONCE_QUERY, fetchPolicy: 'no-cache'})
  .valueChanges
  .pipe(first())
  .subscribe(response => console.log(response.data.nonce);

this.apollo.watchQuery<any>({query: NONCE_QUERY, fetchPolicy: 'no-cache'})
  .valueChanges
  .pipe(first())
  .subscribe(response => console.log(response.data.nonce);

… the value of response.data.nonce is the same.

When I wait for the first request to finish, like:

this.apollo.watchQuery<any>({query: NONCE_QUERY, fetchPolicy: 'no-cache'})
  .valueChanges
  .pipe(first())
  .subscribe(response => {
    console.log(response.data.nonce);

    this.apollo.watchQuery<any>({query: NONCE_QUERY, fetchPolicy: 'no-cache'})
       .valueChanges
       .pipe(first())
       .subscribe(response => console.log(response.data.nonce);
  }

… it works as expected.

I also tried the same requests using this.apollo.query instead of watchQuery but with the same result.

This is the Apollo provider:

{
  provide: APOLLO_OPTIONS,
  useFactory: (httpLink: HttpLink): ApolloClientOptions<any> => {
    return {
      cache: new InMemoryCache(),
      link: httpLink.create({
        uri: 'URL',
        withCredentials: true,
      }),
      defaultOptions: {
        query: {
          fetchPolicy: 'no-cache'
        }
      }
    };
  },
  deps: [HttpLink],
}

How to make Apollo send a new request each time even though another one is pending?



from How to fetch fresh results with each request and no-cache strategy in Apollo GraphlQL and Angular?

No comments:

Post a Comment