Bird
Raised Fist0
React Nativemobile~10 mins

Push notifications with FCM in React Native

Choose your learning style10 modes available
Introduction

Push notifications let your app send messages to users even when they are not using it. FCM (Firebase Cloud Messaging) helps you send these messages easily and reliably.

To alert users about new messages or updates in a chat app.
To remind users about upcoming events or appointments.
To send promotional offers or news in a shopping app.
To notify users about important app changes or alerts.
Syntax
React Native
import messaging from '@react-native-firebase/messaging';

// Request permission to receive notifications
const requestUserPermission = async () => {
  const authStatus = await messaging().requestPermission();
  const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
                  authStatus === messaging.AuthorizationStatus.PROVISIONAL;
  return enabled;
};

// Get FCM token
const getFcmToken = async () => {
  const token = await messaging().getToken();
  return token;
};

// Listen for messages
messaging().onMessage(async remoteMessage => {
  console.log('A new FCM message arrived!', remoteMessage);
});

Use messaging().requestPermission() to ask user permission for notifications.

Use messaging().getToken() to get the device token needed to send notifications.

Examples
This example asks the user for notification permission and logs the result.
React Native
const requestPermission = async () => {
  const authStatus = await messaging().requestPermission();
  const enabled =
    authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
    authStatus === messaging.AuthorizationStatus.PROVISIONAL;
  if (enabled) {
    console.log('Permission granted');
  } else {
    console.log('Permission denied');
  }
};
This listens for incoming messages when the app is in the foreground and logs the notification title to the console.
React Native
messaging().onMessage(async remoteMessage => {
  console.log('New notification: ' + remoteMessage.notification?.title);
});
Sample App

This React Native app requests notification permission on start, listens for messages, and shows the FCM token when the button is pressed.

React Native
import React, {useEffect} from 'react';
import {View, Text, Button, Alert} from 'react-native';
import messaging from '@react-native-firebase/messaging';

export default function App() {
  const requestUserPermission = async () => {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;
    if (enabled) {
      console.log('Permission granted');
    } else {
      console.log('Permission denied');
    }
  };

  const getToken = async () => {
    const token = await messaging().getToken();
    Alert.alert('FCM Token', token);
  };

  useEffect(() => {
    requestUserPermission();
    const unsubscribe = messaging().onMessage(async remoteMessage => {
      Alert.alert('FCM Message', remoteMessage.notification?.title || 'No title');
    });
    return unsubscribe;
  }, []);

  return (
    <View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
      <Text>Push Notifications with FCM</Text>
      <Button title="Get FCM Token" onPress={getToken} />
    </View>
  );
}
OutputSuccess
Important Notes

Always test push notifications on a real device; emulators may not support them fully.

Remember to configure Firebase project and add google-services files to your app.

Handle permissions carefully to respect user privacy and platform rules.

Summary

FCM helps send push notifications to your React Native app.

Request user permission before receiving notifications.

Use messaging().getToken() to get the device token for sending messages.

Practice

(1/5)
1. What is the main purpose of Firebase Cloud Messaging (FCM) in a React Native app?
easy
A. To create UI components
B. To store user data locally
C. To send push notifications to the app users
D. To manage app navigation

Solution

  1. Step 1: Understand FCM's role

    FCM is a service designed to send push notifications to apps.
  2. Step 2: Compare options

    Only To send push notifications to the app users describes sending push notifications, which is FCM's main purpose.
  3. Final Answer:

    To send push notifications to the app users -> Option C
  4. Quick Check:

    FCM = Push notifications [OK]
Hint: FCM is about messaging, not UI or storage [OK]
Common Mistakes:
  • Confusing FCM with local data storage
  • Thinking FCM manages UI or navigation
  • Assuming FCM is for database operations
2. Which React Native Firebase method is used to get the device token for FCM push notifications?
easy
A. messaging().requestPermission()
B. messaging().getToken()
C. messaging().sendMessage()
D. messaging().subscribeToTopic()

Solution

  1. Step 1: Identify token retrieval method

    The method to get the device token is messaging().getToken().
  2. Step 2: Eliminate other options

    requestPermission() asks user permission, sendMessage() sends messages, subscribeToTopic() subscribes to topics.
  3. Final Answer:

    messaging().getToken() -> Option B
  4. Quick Check:

    Get token = getToken() [OK]
Hint: Get token with getToken(), not requestPermission() [OK]
Common Mistakes:
  • Using requestPermission() to get token
  • Confusing sendMessage() with token retrieval
  • Mixing subscribeToTopic() with token methods
3. What will be the output of this code snippet in a React Native app using FCM?
import messaging from '@react-native-firebase/messaging';

async function getToken() {
  const token = await messaging().getToken();
  console.log(token);
}

getToken();
medium
A. Logs the device's FCM token string to the console
B. Throws a syntax error due to missing await
C. Logs 'undefined' because getToken() returns nothing
D. Throws a runtime error because messaging() is undefined

Solution

  1. Step 1: Analyze async function behavior

    The function awaits messaging().getToken(), which returns the device token string.
  2. Step 2: Understand console.log output

    It logs the token string, not undefined or error, assuming messaging is imported correctly.
  3. Final Answer:

    Logs the device's FCM token string to the console -> Option A
  4. Quick Check:

    getToken() returns token string [OK]
Hint: Await getToken() to get token string, then log it [OK]
Common Mistakes:
  • Forgetting await causing Promise logged
  • Assuming getToken() returns undefined
  • Not importing messaging correctly
4. You wrote this code to request permission for notifications but it doesn't work as expected:
import messaging from '@react-native-firebase/messaging';

messaging().requestPermission();
What is the likely problem?
medium
A. requestPermission() is not a valid method
B. You need to import notifications instead of messaging
C. You must call getToken() before requestPermission()
D. You forgot to await the requestPermission() call

Solution

  1. Step 1: Check async method usage

    requestPermission() returns a Promise and should be awaited to complete permission request.
  2. Step 2: Identify missing await effect

    Without await, the permission request may not finish before next steps, causing unexpected behavior.
  3. Final Answer:

    You forgot to await the requestPermission() call -> Option D
  4. Quick Check:

    Await async calls like requestPermission() [OK]
Hint: Always await async permission requests [OK]
Common Mistakes:
  • Not awaiting async permission calls
  • Thinking requestPermission() is invalid
  • Calling getToken() before permission
5. You want to send a push notification only if the user has granted permission. Which code snippet correctly checks permission and then gets the FCM token in React Native?
hard
A. const authStatus = await messaging().requestPermission(); if (authStatus === messaging.AuthorizationStatus.AUTHORIZED) { const token = await messaging().getToken(); console.log(token); }
B. const token = await messaging().getToken(); if (token) { await messaging().requestPermission(); console.log(token); }
C. await messaging().getToken(); await messaging().requestPermission(); console.log('Permission and token done');
D. messaging().requestPermission(); messaging().getToken(); console.log('Permissions requested and token fetched');

Solution

  1. Step 1: Check permission before token

    const authStatus = await messaging().requestPermission(); if (authStatus === messaging.AuthorizationStatus.AUTHORIZED) { const token = await messaging().getToken(); console.log(token); } requests permission and checks if authorized before getting token.
  2. Step 2: Verify async and order correctness

    const authStatus = await messaging().requestPermission(); if (authStatus === messaging.AuthorizationStatus.AUTHORIZED) { const token = await messaging().getToken(); console.log(token); } awaits both calls and uses correct AuthorizationStatus check.
  3. Final Answer:

    const authStatus = await messaging().requestPermission(); if (authStatus === messaging.AuthorizationStatus.AUTHORIZED) { const token = await messaging().getToken(); console.log(token); } -> Option A
  4. Quick Check:

    Check permission first, then get token [OK]
Hint: Request permission first, then get token if authorized [OK]
Common Mistakes:
  • Getting token before permission
  • Not awaiting async calls
  • Ignoring authorization status check
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard