invertase / react-native-firebase-starter

DEPRECATED: For RNFB v5 only.
https://rnfirebase.io/docs
Other
1.17k stars 334 forks source link

Handling notifications with FCM #112

Closed jajosheni closed 5 years ago

jajosheni commented 5 years ago

First of all, this repo is cool and very helpful. 2nd, THIS IS NOT AN ISSUE.

Because i spent time figuring out how to handle notifications i would like to share a snippet of code. I hope somebody will find it helpful.

 componentDidMount() {
    firebase.messaging().hasPermission()
      .then(enabled => {
        if (enabled) {
          console.log('permissions Granted.');
        } else {
          console.log('i dont have permissions');
        }
      });

    firebase.notifications().getInitialNotification()
      .then((notificationOpen: NotificationOpen) => {
        if (notificationOpen) {
          // App was opened by a notification
          // Get the action triggered by the notification being opened
          const action = notificationOpen.action;
          // Get information about the notification that was opened
          const notification: Notification = notificationOpen.notification;
          console.log('initialNotification: ', notification);
          console.log('action: ', action);
        }
      });

    this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => {
      // Process your notification as required
      console.log('DisplayedListener: ', notification);
    });
    this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
      console.log('notificationListener: ', notification);
    });

    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
      // Get the action triggered by the notification being opened
      const action = notificationOpen.action;
      // Get information about the notification that was opened
      const notification: Notification = notificationOpen.notification;
      console.log('notificationOpenedListener: ', notification);
      console.log('action: ', action);
    });
  }

  componentWillUnmount() {
    this.notificationDisplayedListener();
    this.notificationListener();
    this.notificationOpenedListener();
  }