Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get FCM token in React-Native

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 };
like image 454
Shashika Avatar asked Apr 19 '26 09:04

Shashika


1 Answers

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

like image 72
dakini Avatar answered Apr 21 '26 03:04

dakini