Ad

How Do I Send Push Notifications In Reactjs On Android

The scenario is this:

Announcements will be written through Google Spreadsheet and will be retrieved on the web app page (which is I'm using is React JS)

I need to let the user know that there's a new announcement

How do I implement push notification from that

I've tried using Firebase Cloud Messaging but I can't figure out how the JSON works

here is the link is used as reference

firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');

firebase.initializeApp({
  messagingSenderId: "ID here"
});

const messaging = firebase.messaging();

Push-notification.js

import firebase from 'firebase';

export const initializeFirebase = () => {
  firebase.initializeApp({
    apiKey: "key",
    authDomain: "domain",
    databaseURL: "url",
    projectId: "demo",
    storageBucket: "",
    messagingSenderId: "ID",
    appId: "app id"
  });

  navigator.serviceWorker
    .register('/firebase-messaging-sw.js')
    .then((registration) => {
      firebase.messaging().useServiceWorker(registration);
    });
}

export const firebaseNotifications = async () => {
    try {
      const messaging = firebase.messaging();
      await messaging.requestPermission();
      const token = await messaging.getToken();
      console.log('Token:', token);

      return token;
    } catch (error) {
      console.error(error);
    }
  }

All the code I used is in the link given

There are still no errors encountered. But I've hit a roadblock and that I can't seem to work this out.

Ad

Answer

I figured this out and just follow properly the setup in firebase

and use postman to send JSON parameters to test the push notification to your android

Ad
source: stackoverflow.com
Ad