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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With