Get FCM token in React-Native

Shashika picture Shashika · Jul 22, 2019 · Viewed 9.5k times · Source

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 };

Answer

Yogesch picture Yogesch · Jun 2, 2021
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