loading...

Automatically watch queries in Apollo GraphQL

bdbch profile image Dominik Biedebach ・1 min read

I just worked on one of our hooks that fetches data from our Apollo GraphQL server, but I noticed that my data won't be updated in the local cache when the current subscription is not open.

This is how my code looked like before:

const chatId = '123456';

client.query({
  query: GET_CHAT_MESSAGES,
  variables: {
    chatId,
  }
}).then(res => {
  // do stuff here
})

This query would not update after being run once because Apollo saves all queries locally without knowing about potential changes.

When mutations were made, the chat view would still show an old state, even when my subscription would rewrite the cache.

What I had to do was using client.watchQuery instead of client.query. watchQuery allows you to watch a query for potential changes via mutations and re-run the query if needed. It also allows you to use the 'cache-and-network' fetch policy.

Now my code looks like this:

const chatId = '123456';

const querySubscription = client.watchQuery({
  query: GET_CHAT_MESSAGES,
  variables: {
    chatId,
  },
  fetchPolicy: 'cache-and-network'
}).subscribe({
  next: ({ data }) => { // do stuff },
  error: (e) => console.error(e)
})

Just make sure to disconnect the subscription if it is not needed anymore with querySubscription.unsubscribe().

Posted on by:

bdbch profile

Dominik Biedebach

@bdbch

I produce code. - Prefers React over Vue - Prefers VSCode over any other editor - Likes React Native - Absolutely loves GraphQL / Apollo

Discussion

pic
Editor guide
 

Thank you! This is what I've been missing!