Chris
Chris

Reputation: 19

React-Native Firebase Push Notification onClick to a specific page within my app

I want to make my push notification to be able to take me to a specific page 'Fingerprint' once its clicked. As of now the push notification does nothing when clicked except opening the app if its in the background. I have searched online, and trial & error for two days now to no avail. Any help would be appreciated.

import React, {Component} from 'react';
    import {Platform, StyleSheet, Text, View, Alert, AsyncStorage, Button} from 'react-native';
    import firebase from 'react-native-firebase';





type Props = {};
export default class testapp extends Component<Props> {


  async componentDidMount() {
    this.checkPermission();
    this.createNotificationListeners(); //add this line
  }

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

  //1
  async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
    if (enabled) {
      this.getToken();
    } else {
      this.requestPermission();
    }
  }

  //3
  async getToken() {
    let fcmToken = await AsyncStorage.getItem('fcmToken');
    if (!fcmToken) {
      fcmToken = await firebase.messaging().getToken();
      if (fcmToken) {
        // user has a device token
        console.log('fcmToken:', fcmToken);
        await AsyncStorage.setItem('fcmToken', fcmToken);
      }
    }
    console.log('fcmToken:', fcmToken);
  }

  //2
  async requestPermission() {
    try {
      await firebase.messaging().requestPermission();
      // User has authorised
      this.getToken();
    } catch (error) {
      // User has rejected permissions
      console.log('permission rejected');
    }
  }

  async createNotificationListeners() {
    /*
    * Triggered when a particular notification has been received in foreground
    * */
    this.notificationListener = firebase.notifications().onNotification((notification) => {
      const { title, body } = notification;
      console.log('onNotification:');

        const localNotification = new firebase.notifications.Notification({
          sound: 'sampleaudio',
          show_in_foreground: true,
        })
        .setSound('sampleaudio.wav')
        .setNotificationId(notification.notificationId)
        .setTitle(notification.title)
        .setBody(notification.body)
        .android.setChannelId('fcm_FirebaseNotifiction_default_channel') // e.g. the id you chose above
        .android.setSmallIcon('@drawable/ic_launcher') // create this icon in Android Studio
        .android.setColor('#000000') // you can set a color here    
        // .setClickAction(()=>alert('test'))   
        .android.setPriority(firebase.notifications.Android.Priority.High);


        firebase.notifications()
          .displayNotification(localNotification)
          .catch(err => console.error(err));
    });

    const channel = new firebase.notifications.Android.Channel('fcm_FirebaseNotifiction_default_channel', 'UniFinalApp', firebase.notifications.Android.Importance.High)
      .setDescription('Demo app description')
      .setSound('sampleaudio.wav');
    firebase.notifications().android.createChannel(channel);

    /*
    Code would probably go in the section below
    * 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) => {
      const { title, body } = notificationOpen.notification;
      console.log('onNotificationOpened:');

      // Alert.alert(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;
      console.log('getInitialNotification:');
      Alert.alert(title, body)
    }
    /*
    * Triggered for data only payload in foreground
    * */
   this.messageListener = firebase.messaging().onMessage((message) => {
    //process data message
    console.log("JSON.stringify:", JSON.stringify(message));
  });
}
render() {
  // const {navigate}=this.props.navigation;
    return (
      <View >


      </View>
    );
  }
}

Upvotes: 1

Views: 7080

Answers (2)

manirul Islam
manirul Islam

Reputation: 11

I am trying to get the notification like this but its also not working. This is working for background means when an app is close

const notificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
    const {_notificationId} = notificationOpen.notification.data
    if (_notificationId) {
     redirect('chatform', {id: _notificationId})
    }
}

Upvotes: 0

rabbit87
rabbit87

Reputation: 3205

Inside the documentation for React-native-firebase; there's a section on how to handles data from notification. What you can do is to send data inside the notification that will tell the app what to do. For example:

firebase.notifications().getInitialNotification()
.then((notificationOpen: NotificationOpen) => {
   if (notificationOpen) {
      // App was opened by a notification
      const notification: Notification = notificationOpen.notification;  
      const data = notificationOpen.notification._data;
        if (data.action === 'openChat') {
          //Code to open Chat screen  
        }
   }
});

Or you can use the data from the notification to set some flags, and then once the user enters a certain screen (like after logged-in) checks the flags to see if certain action need to be done.

Upvotes: 2

Related Questions