skip to Main Content

I have implemented firebase background notification messages, therefore I had to put firebase-messaging-sw.js file in public folder. I need to access state, which determines language of the website inside firebase-messaging-sw.js. I am using useContext to manage state. Here is the code of firebase-messaging-sw.js :

importScripts("https://www.gstatic.com/firebasejs/9.0.2/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/9.0.2/firebase-messaging-compat.js");


const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
};

firebase.initializeApp(firebaseConfig)
const messaging = firebase.messaging();


const openDatabase = async () => {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open('qapp-firebase-messages', 1);

    request.onerror = () => {
      console.error('Error opening IndexedDB database.');
      reject(request.error);
    };

    request.onsuccess = (event) => {
      resolve(request.result);
    };

    request.onupgradeneeded = (event) => {
      const db = event.target.result;
      if (!db.objectStoreNames.contains('messages')) {
        const objectStore = db.createObjectStore('messages', { keyPath: 'id', autoIncrement: true });
      }
    };
  });
};


const storeMessage = async (messageData) => {
  const db = await openDatabase();
  const transaction = db.transaction('messages', 'readwrite');
  const objectStore = transaction.objectStore('messages');
  const request = objectStore.put(messageData);
  transaction.onerror = (error) => {
    console.error('Error storing message in IndexedDB:', error);
  };
};

messaging.onBackgroundMessage((payload) => {
  console.log("backgroundmessages recieved")
  console.log(payload.data)
  storeMessage(payload.data);
});

There should be some way to connect to source code from public folder.

2

Answers


  1. You can use the below modules to have the exact service in react src folder only:

    import { initializeApp } from "firebase/app";
    import { getMessaging } from "firebase/messaging/sw";
    
    Login or Signup to reply.
  2. we can not use useState or any other hook out side a react Component. but here you can use localStorage or sessionStorage to get selected language.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search