How To Get FCM token in React-Native : A Step By Step Guide

 In This Blog, How to get firebase cloud messaging token in android device and set up push notification using firebase 


Google offers a tool called Firebase Cloud Messaging (FCM) that allows users to deliver push notifications to mobile devices. You can combine FCM with React Native to allow push notifications in your application. An outline of how to obtain the FCM token is provided here.


Set up Firebase in your React Native project:

Using the Firebase console (https://console.firebase.google.com/), begin by starting a new project. To add your app to the Firebase project, follow the directions. Ensure that you download and add to your React Native project the GoogleServices.json file for Android or the GoogleService-Info.plist file for iOS.











Enable Cloud Messaging API



After Enabled Cloud Messaging API you can get a server key.Push notifications, messages, and data can be sent to mobile devices or web apps via cloud messaging APIs. By sending pertinent and timely information straight to consumers' devices, these APIs let developers interact with people.

Install Firebase Messaging SDK



  
yarn add @react-native-firebase/app
yarn add @react-native-firebase/messaging


Retrieve the FCM token

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

    useEffect(() => {
      const getFCMToken = async () => {
        const fcmToken = await messaging().getToken();
        if (fcmToken) {
          console.log('FCM Token:', fcmToken);
          // Send this token to your server for later use
        } else {
          console.log('No FCM token available');
        }
      };

      getFCMToken();

      // Optionally, listen to token refresh events
      const unsubscribe = messaging().onTokenRefresh((newToken) => {
        console.log('FCM Token refreshed:', newToken);
        // Send the new token to your server
      });

      return unsubscribe;
    }, []);




After configuring Firebase Messaging, use the getToken function to obtain the FCM token. To deliver push notifications, the device must have this token, which gives it a unique identity. Typically, your React Native component's useEffect hook or any other suitable lifecycle method allow you to access this token.

Tokens for FCM may be updated on a regular basis. When a token refresh event happens, be sure to pay attention to it and update your server with the new token.

Tokens for FCM may be updated on a regular basis. When a token refresh event happens, be sure to pay attention to it and update your server with the new token.
Post a Comment (0)
Previous Post Next Post