Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsubscribe subscription in Apollo Client

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?

like image 522
V0iDiFiER Avatar asked Jul 23 '18 10:07

V0iDiFiER


Video Answer


1 Answers

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.

like image 90
Pedro Baptista Afonso Avatar answered Oct 20 '22 00:10

Pedro Baptista Afonso