How to unsubscribe from events


We have a react app and have made a custom button for launching Intercom.

The button have onHide and onShow listeners (window.Intercom('onHide', setIsOpen))) to show a close icon on the button when Intercom is showing.

When the user hides the menu, with the button, we would like to unsubscribe to the onHide and onShow events. How can we do that?

TLDR: How to unsubscribe form onHide and onShow events?

Hey @kruse ! At the moment, there isn’t a way to unsubscribe to the onHide and onShow events. If possible, I’d love it if I could get a little more clarification on your current flow. What is your setIsOpen function doing?
Are you attaching a close button to our actual messenger? Thanks!

Our Intercom button is showing “Close” when the Intercom window is open.
setIsOpen changes the button state to either showing “Close” og “Get help”

The button is not attached to the Intercom window but uses the custom_launcher_selector

If I’m understanding this right you have a custom launcher button on your page. The button displays either “Close” or “Get help”. If the Messenger is open then the button should display “Close” and if the Messenger is closed then the button should display “Get help”. To figure out if the button is closed or open you listen for changes to the event listener onHide and onShow. If either of these events occur then you call your setIsOpen which switches what the button displays.

From what you’ve said it sounds like this is working correctly. Are there any issues that you’re running into with this setup? I want to make sure we’re on the same page as to why you’re looking for the ability to unsubscribe for these listeners :+1:

That is correct and that part works.
The problem is the user can hide the menu with the custom launcher button.
When the menu is closed React destroys the component.

When the menu is opened again and the user clicks the custom launcher button i get the following error:

Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

onShow is trying to call a function there no longer exist.

Also, as the component is created again it calls onHide and onShow with a new setIsOpen and setIsClosed.

onUnreadCountChange is also gonna be a problem, if that is fired while the component is hidden.

Thanks for the insights!

I can’t say I’ve really worked with React that much but I’d like to think there’s a better way of avoiding this or handling it.

It looks like some suggestions to avoid the error are to check if the component is mounted or not:

If you do end up finding a good way of doing this with React then do let us know :slightly_smiling_face: