<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Muhammad Ahsan</title>
    <description>The latest articles on DEV Community by Muhammad Ahsan (@ahsan131hub).</description>
    <link>https://dev.to/ahsan131hub</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F851475%2Fdcaae8ca-2ade-43db-9bf6-35f8a820843a.jpeg</url>
      <title>DEV Community: Muhammad Ahsan</title>
      <link>https://dev.to/ahsan131hub</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ahsan131hub"/>
    <language>en</language>
    <item>
      <title>React Native Fire Base Push Notification Using Topics.</title>
      <dc:creator>Muhammad Ahsan</dc:creator>
      <pubDate>Thu, 21 Apr 2022 22:09:30 +0000</pubDate>
      <link>https://dev.to/ahsan131hub/react-native-fire-base-push-notification-using-topics-2fnf</link>
      <guid>https://dev.to/ahsan131hub/react-native-fire-base-push-notification-using-topics-2fnf</guid>
      <description>&lt;h2&gt;
  
  
  Why Use Topics Notification.
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;For example, Users of a sports app could subscribe to automatic updates in live game scores for their favorite teams.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://reactnative.dev/docs/environment-setup"&gt;React Native - Setting up the development environment&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://console.firebase.google.com/u/0/"&gt;Create a new Firebase project&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Firstly install firebase cloud messaging package and to communication.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Install &amp;amp; setup the app module&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;npm install @react-native-firebase/app&lt;/code&gt;&lt;br&gt;
&lt;strong&gt;Install the messaging module&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;npm install @react-native-firebase/messaging&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Client Side&lt;/strong&gt;&lt;br&gt;
firstly create a rnFireBase.ts &lt;br&gt;
imports:&lt;code&gt;import messaging from "@react-native-firebase/messaging";&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
Add Following code to request a permission from client for to recieve the notifications.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const requestUserPermission = async () =&amp;gt; {
  const authStatus = await messaging().requestPermission();
  const enabled =
    authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
    authStatus === messaging.AuthorizationStatus.PROVISIONAL;
  if (enabled) {
    console.log("Authorization status:", authStatus);
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;then we have to add code, so that a user can subscribe to a particular topic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const subscribeTopic = async (topic) =&amp;gt; {
  messaging()
    .subscribeToTopic(topic)
    .then(() =&amp;gt; console.log("Subscribed to topic:", topic))
    .catch((e) =&amp;gt; {
      console.log(e);
    });
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import messaging from "@react-native-firebase/messaging";
import { useEffect } from "react";
import { Alert } from "react-native";

import { requestUserPermission } from "./rnfirbase";

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

export default RemotePushController;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now add RemotePushController any where you want. I have added RemotePushController in my root component.&lt;br&gt;
Cheers:) we are all done client side, Let's in to the &lt;/p&gt;
&lt;h2&gt;
  
  
  Server Side
&lt;/h2&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now create a notify.ts for to send&lt;br&gt;
 notifications&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { messaging } from "./initFirebase";

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

export default sendNotificationToClient;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create sendNotifications.ts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as notify from "./notify";
export const notificationSender = async (topic: string, message: string) =&amp;gt; {
  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);
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You are all done. all you need to do now is to just call&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;notificationSender(
            "new-listing",
            `This is a string message is being to sent with notification `
          );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;anywhere in your server code.&lt;/p&gt;

</description>
      <category>firebase</category>
      <category>reactnative</category>
      <category>typescript</category>
      <category>graphql</category>
    </item>
  </channel>
</rss>
