Unsubscribe subscription in Apollo Client

V0iDiFiER picture V0iDiFiER · Jul 23, 2018 · Viewed 11k times · Source

In my component, I have this code:

componentDidMount () {
  // Setup subscription listener
  const { client, match: { params: { groupId } } } = this.props
  client.subscribe({
    query: HOMEWORK_IN_GROUP_SUBSCRIPTION,
    variables: { groupId },
  }).subscribe({
    next ({ data }) {
      const cacheData = client.cache.readQuery({
        query: GET_GROUP_QUERY,
        variables: { groupId },
      })

      const homeworkAlreadyExists = cacheData.group.homeworks.find(
        homework => homework._id == data.homeworkInGroup._id
      )
      if (!homeworkAlreadyExists) {
        client.cache.writeQuery({
          query: GET_GROUP_QUERY,
          variables: { groupId },
          data: { ...cacheData,
            group: { ...cacheData.group,
              homeworks: [ ...cacheData.group.homeworks,
                data.homeworkInGroup,
              ],
            },
          },
        })
      }
    },
  })
}

The problem is that this component will re-subscribe when mounted and will mantain subscribed even if unmounted.

How can I unsubscribe my component?

Answer

Pedro Baptista Afonso picture Pedro Baptista Afonso · Jul 23, 2018

client.subscribe({ ... }).subscribe({ ... }) will return an instance for your subscription, that you can use to unsubscribe.

So something like:

componentDidMount () {
  // Setup subscription listener
  // (...)
  this.querySubscription = client.subscribe({
    // (...)
  }).subscribe({
    // (...)
  })
}

componentWillUnmount () {
  // Unsibscribe subscription
  this.querySubscription.unsubscribe();
}

You can get some inspiration by looking at how react-apollo manages this situation looking at their code base.

NOTE: My best advice would be to use Subscription component, that will manage everything for you.