4

I have some Apollo-Hooks code that uses useSubscription to listen for event changes in a subscription:

useSubscription<MySubscriptionUpdated>(MySubscription, {
    onSubscriptionData: async ({ client, subscriptionData: { data } }) => {
      if (!data) {
        return;
      }
      ...

This code automatically updates the cache on the response, which is great in most circumstances

However, I need to do some result-processing after the response is received, yet prior to the cache being updated.

Does anyone know of a way to use useSubscription hook, and not have the cache be automatically updated?

The response will ultimately always have an entity with __typename in it.

Brett
  • 11,637
  • 34
  • 127
  • 213

2 Answers2

4

You can change fetchPolicy for each subscription. The default value is cache-first. To disable cache must set fetchPolicy to no-cache. For get more detail see apollo official document.

useSubscription<MySubscriptionUpdated>(MySubscription, {
    fetchPolicy: "no-cache",
    onSubscriptionData: async ({ client, subscriptionData: { data } }) => {
      if (!data) {
        return;
      }
      ...
Masih Jahangiri
  • 9,489
  • 3
  • 45
  • 51
0

So, you can do a manual cache update, it would look something like this

apollo.mutate({
  mutation: createTaskMutation,
  variables: item,
  update: (cache, { data }) => {
    try {
      let { allTasks } = cache.readQuery({ query: getTasks });
      allTasks.push(data);
      cache.writeQuery({ //
        query: getTasks,
        data: {
            'allTasks': allTasks
        }
      });
    } catch (e) {
        // We should always catch here,
        // as the cache may be empty or the query may fail
    }
});
Duma Cristian
  • 577
  • 5
  • 11
  • Even when you use an `update` function, Apollo does an auto-update before calling your `update` unless you use `fetchPolicy: 'no-cache'`. OP was asking how to prevent that auto-update. – Andy Mar 25 '20 at 03:46