9

In my React-Native application, I have to use firebase notifications. So I created this library. Have I done this in the correct way? How can I test this to check if this works properly? What I want is to return the FCM token here.

/** Firebase Cloud Messaging Methods */
import firebase from 'react-native-firebase';

const getToken = async () => {
  try {
    const token = await firebase.messaging().getToken();
    if (token) return token;
  } catch (error) {
    console.log(error);
  }
};

const getFCMToken = async () => {
  try {
    const authorized = await firebase.messaging().hasPermission();
    const fcmToken = await getToken();

    if (authorized) return fcmToken;

    await firebase.messaging().requestPermission();
    return fcmToken;
  } catch (error) {
    console.log(error);
  }
};

export { getFCMToken };
Shashika Virajh
  • 8,497
  • 17
  • 59
  • 103

3 Answers3

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

const checkToken = async () => {
 const fcmToken = await messaging().getToken();
 if (fcmToken) {
    console.log(fcmToken);
 } 
}

checkToken();

References: https://rnfirebase.io/messaging/usage and https://github.com/invertase/react-native-firebase-docs/blob/master/docs/messaging/device-token.md

ahron
  • 803
  • 6
  • 29
0

To check if you have implemented notification correctly. You have to go to

Firebase Console

Click on 'Cloud Messaging' and then "New Notification" Send a test notification. If you receive a notification then your code is fine.

BTW you should use the "Topic" implementation rather than the "Token" implementation. It will make this process of sending Notifications very easy and manageable.

Usman Kazmi
  • 526
  • 4
  • 4
-2

Getting FCM notification using 3rd party library always painful for debugging, So Always i would recommend use Native call for such API using react-native bridge.because react-native library should only use if common functionality used in Android and IOS. this is updated

MR. Kumar
  • 661
  • 8
  • 25