DEV Community

Cover image for React Native Fire Base Push Notification Using Topics.
Muhammad Ahsan
Muhammad Ahsan

Posted on

React Native Fire Base Push Notification Using Topics.

Why Use Topics Notification.

FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose a Topic, user Subscribes to that Topic and Fire-Cloud-Messaging handles routing and delivering the message reliably to the right devices.

For example, Users of a sports app could subscribe to automatic updates in live game scores for their favorite teams.

Prerequisites

Before getting started, I assume you are able to create a project with React Native and that you have an active Firebase project. If you do not meet these prerequisites, follow the links below:

Firstly install firebase cloud messaging package and to communication.

Install & setup the app module
npm install @react-native-firebase/app
Install the messaging module
npm install @react-native-firebase/messaging

Client Side
firstly create a rnFireBase.ts
imports:import messaging from "@react-native-firebase/messaging";

Add Following code to request a permission from client for to recieve the notifications.

export const requestUserPermission = async () => {
  const authStatus = await messaging().requestPermission();
  const enabled =
    authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
    authStatus === messaging.AuthorizationStatus.PROVISIONAL;
  if (enabled) {
    console.log("Authorization status:", authStatus);
  }
};
Enter fullscreen mode Exit fullscreen mode

then we have to add code, so that a user can subscribe to a particular topic.

export const subscribeTopic = async (topic) => {
  messaging()
    .subscribeToTopic(topic)
    .then(() => console.log("Subscribed to topic:", topic))
    .catch((e) => {
      console.log(e);
    });
};
Enter fullscreen mode Exit fullscreen mode

Now we can call subscribeTopic anywhere to subscribe a any specific Topic.
For Example in index.js just do : subscribeTopic("new-listing");
Now we need to do one more simple Thing For Client Side is to add React Native Component just like below.

import messaging from "@react-native-firebase/messaging";
import { useEffect } from "react";
import { Alert } from "react-native";

import { requestUserPermission } from "./rnfirbase";

const RemotePushController = () => {
  //if app is in background then also handle the notification
  messaging().setBackgroundMessageHandler(async function (remoteMessage) {
    console.log("Message handled in the background!", remoteMessage); 
  });
  useEffect(() => {
    requestUserPermission();
   //handles notifcations
    messaging().onMessage(async (remoteMessage) => {
      Alert.alert("A new FCM message arrived!", JSON.stringify(remoteMessage));
    });
  }, []);
  return null;
};

export default RemotePushController;

Enter fullscreen mode Exit fullscreen mode

Now add RemotePushController any where you want. I have added RemotePushController in my root component.
Cheers:) we are all done client side, Let's in to the

Server Side

For server side we need to firstly initialise firebase,
skip if you have already initialised but do add this line if not already there export const messaging = admin.messaging();

import admin from "firebase-admin";

import serviceAccount from "./service_account.json";

const app = admin.initializeApp({
  credential: admin.credential.cert({
    privateKey: serviceAccount.private_key,
    clientEmail: serviceAccount.client_email,
    projectId: serviceAccount.project_id,
  }),
});
export const messaging = admin.messaging();
export const firebaseApp = app;

Enter fullscreen mode Exit fullscreen mode

Now create a notify.ts for to send
notifications

import { messaging } from "./initFirebase";

export const sendNotificationToClient = async (topic: string, data: any) => {
  // console.log(messaging);
  messaging
    .sendToTopic(topic, data)
    .then((response) => {
      console.log(`Notifications sent:${response}successful `);
    })
    .catch((error) => {
      console.log("Error sending message:", error);
    });
};

export default sendNotificationToClient;

Enter fullscreen mode Exit fullscreen mode

Create sendNotifications.ts

import * as notify from "./notify";
export const notificationSender = async (topic: string, message: string) => {
  try {
    // If we want to save topic to DataBase then we do that here;
    const messagetoSend = {
      notification: {
        title: "New Test Message",
        body: message,
      },
    };
    notify.sendNotificationToClient(topic, messagetoSend);
  } catch (err) {
    console.log("🚀 ~ file: Message.ts ~ line 19 ~ addMessage ~ err", err);
  }
};

Enter fullscreen mode Exit fullscreen mode

You are all done. all you need to do now is to just call

notificationSender(
            "new-listing",
            `This is a string message is being to sent with notification `
          );
Enter fullscreen mode Exit fullscreen mode

anywhere in your server code.

Oldest comments (1)

Collapse
 
ahsan131hub profile image
Muhammad Ahsan

Your comments and feedback are welcome.