3

I'm trying to catch a notification in the foreground with react native, using react-native-firebase.

If the app is in the background, the notification is being shown only once as it should (obviously because it's not handled within the app). But when the app is in the foreground, the callback function to catch the notification is triggered multiple times, in a quite random fashion. If I refresh the app and then send again usually the number grows exponentially, and can reach 12 times or more.

My very simple code:

import React, { Component } from 'react';
import {
  View,
  Text,
} from 'react-native';


import messaging from '@react-native-firebase/messaging';


class App extends Component {

  async componentDidMount() {
    messaging().onMessage(async message => console.log("message received!!!")
  }


  render(){
    return (
      <View>
        <Text>Notification App</Text>
      </View>
    )
  }
}

export default App;

To send the notification, I'm using Firebase cloud messaging test system:

enter image description here

I know my FCM token id so it's easy. My question is how can I make the call back function messaging().onMessage trigger only once

sir-haver
  • 3,096
  • 7
  • 41
  • 85

2 Answers2

1

if you don't remove the messaging listener when the app component is unmounted, then your app can have multiple listeners and then receive message multiple times. try to edit your code like this to delete listener when component unmount:

async componentDidMount() {
    this.messageListener = messaging().onMessage(async message => console.log("message received!!!")
  }

componentWillUnmount() {
    this.messageListener();
}
Mahdi N
  • 2,128
  • 3
  • 17
  • 38
  • 1
    Thank you very much, I found out that the problem was the hot reload, apperantly in you refresh the app using hot reload it doesn't remove the listener, so you need to refresh from the device manually. Nevertheless thank you very much for your input it's a good practice to remove the listener of course – sir-haver Apr 15 '20 at 11:46
1

I found out that the problem was the hot reload, apperantly in you refresh the app using hot reload it doesn't remove the listener, so you need to refresh from the device manually.

sir-haver
  • 3,096
  • 7
  • 41
  • 85
  • So this problem doesn't appear in the prod? – Aymen Jan 30 '21 at 20:17
  • I was facing this issue even when my app was distributed to a tester through firebase app distribution? Any chance what can be the case? I had removed the listener suggested above. – Akshay Shenoy Nov 24 '21 at 14:59