4

I am using react-native firebase for push notification and they are working fine. The notifications are coming right. The problem I'm facing is that when I receive notification, the "title" and "body" of the notification payload is coming to be undefined.

While debugging, I checked the body and title that I'm sending and I found that it is the right data that I want to send.

this is where I am sending push notification.

sendPushNotification = async (fcmToken, title, body) => {
const payload = {
  to: fcmToken,
  notification: {
    title: title,
    body: body,
    sound: "true"
  }
}

fetch("https://fcm.googleapis.com/fcm/send", {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'key=*****'
  },
  body: JSON.stringify(payload),
})
  .then((response) => response.json())
  .then((responseJson) => {
    console.log(responseJson)
  })
  .catch((error) => {
    console.log(error);
  });

}

And This is where I am using notification listeners and title and body and sound is showing undefined.

async createNotificationListeners(nav) {
    /*
    * Triggered when a particular notification has been received in foreground
    * */
    this.notificationListener = firebase.notifications().onNotification( async (notification) => {
            const { title, body } = notification;
            await this.getConnectionsRequests();
            console.log("we are here")
            //this.showAlert(title, body);
    });

    /*
    * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
    * */
    this.notificationOpenedListener = firebase.notifications().onNotificationOpened( async (notificationOpen) => {
            const { title, body } = notificationOpen.notification;
            nav.navigate("MyChats")
            await this.getConnectionsRequests();
            //this.showAlert(title, body);
    });

    /*
    * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
    * */
    const notificationOpen = await firebase.notifications().getInitialNotification();
    if (notificationOpen) {
            const { title, body } = notificationOpen.notification;
            nav.navigate("MyChats")
            // this.showAlert(title, body);
    }
    /*
    * Triggered for data only payload in foreground
    * */
    this.messageListener = firebase.messaging().onMessage((message) => {
    //process data message
    console.log(JSON.stringify(message));
    });
    } 

I am using these listeners in another screen as followed:

componentDidMount = async () => {
    await this.props.store.createNotificationListeners(this.props.navigation);

}

When notificationOpenedListener is being called, the title and body should be the same as the one I send using sendPushNotification().

Any help would be appreciated. Thank you.

Tanvir Singh
  • 119
  • 9

0 Answers0