Categories
Javascript Uncategorized

How to Get Data from FCM while App is in Background in React Native?

The notifications module in React Native Firebase has support for both remote (FCM) and local notifications. Firebase Cloud Messaging (FCM) is a great way to notify users about something you want them to know. But you can do more instead of showing only the message to the client.

So, how do you get data from FCM while the app is running in the background in React Native?

This is handled appropriately by Firebase SDK. When the user taps on the notification, the app receives payload associated with that notification. Here’s the code you can use to do that error-free.

async createNotificationListeners() {
/*
 Triggered when a particular notification has been received in foreground
*/
this.notificationListener = 
 firebase.notifications().onNotification((notification), function() {
   const { title, body } = notification;
   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((notificationOpen), function(){
   const { title, body } = notificationOpen.notification;
    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;
   this.showAlert(title, body);
}

}

Once you add the above-mentioned set of codes and run the simulation, you get the desired results. Seems good! Comment how it works for you!