DEV Community

bdbch
bdbch

Posted on

Automatically watch queries in Apollo GraphQL

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
})
Enter fullscreen mode Exit fullscreen mode

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)
})
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Collapse
 
danthul profile image
Dan Thul

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