0

In my React Native app I have two screens screenA and screenB. I'm using react-navigation@4.x and I navigate from screenA to screenB with this.props.navigation.navigate('screenB') and back with this.props.navigation.goBack().

I'm using OneSignal, and when screenA mounts I add a OneSignal event listener.

screenA

OneSignal.addEventListener('opened', () => console.log(this.props.navigation.state.routeName));

I have the same code in screenB, and up until this point, it works as expected. When I'm on screenA and open a push notification, it logs screenA, and when I'm on screenB it logs screenB, because screenB's event listener overrides screenA's.

However, when I navigate back to screenA, screenB's event listener is still in place, so I add this code to screenB to remove its event listener:

screenB

componentWillUnmount() {
  OneSignal.removeEventListener('opened');
}

and to get screenA to re-invoke its event listener, I add this code:

screenA

componentDidUpdate(prevProps) {
  if (!prevProps.isFocused && this.props.isFocused) {
    OneSignal.addEventListener('opened', () => console.log(this.props.navigation.state.routeName));
  }
}

**The Problem: **

This isFocused condition is triggered when I return to screenA, so the addEventListener code block is reached, but the event listener isn't successfully added.

Does anyone know how I can approach troubleshooting this?

gkeenley
  • 6,088
  • 8
  • 54
  • 129

2 Answers2

0

See here

To remove event handlers, the function specified with the addEventListener() method must be an external function, like in the example above (myFunction). Anonymous functions, like "element.removeEventListener("event", function(){ myScript });" will not work

So, create a function and provide the SAME reference to add/remove event listeners.

Like this

componentDidMount() {
  window.addEventListener('opened', this.eventListenerFun);
}

componentWillUnmount() {
  window.removeEventListener('opened', this.eventListenerFun);
}

eventListenerFun = () => { 
  // code of your fun goes here....
  //console.log(this.props.navigation.state.routeName);
}

Also see here

gdh
  • 13,114
  • 2
  • 16
  • 28
0

According to React Navigation's Documentation: Consider a stack navigator with screens A and B. After navigating to A, its componentDidMount is called. When pushing B, its componentDidMount is also called, but A remains mounted on the stack and its componentWillUnmount is therefore not called.

When going back from B to A, componentWillUnmount of B is called, but componentDidMount of A is not because A remained mounted the whole time.

Read more...

Kashan Haider
  • 1,036
  • 1
  • 13
  • 23