🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
Book a DemoInstallSign in
Socket

react-fcm-notification

Package Overview
Dependencies
Maintainers
0
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-fcm-notification

React components/hooks for managing Google FCM tokens register/unregister

1.2.1
latest
Source
npm
Version published
Weekly downloads
2
Maintainers
0
Weekly downloads
 
Created
Source

react-fcm-notification

react-fcm-notification is a React library designed to simplify the implementation of notification features using Firebase Cloud Messaging (FCM). It provides token management and notification permission state management, all accessible as React components.

Features

  • Firebase Cloud Messaging Support: Simplifies FCM token retrieval and deletion.
  • Notification Permission Management: Offers hooks for managing browser notification permissions.
  • Customizable: Allows custom logic integration during token retrieval and deletion.
  • Simple API: Easy to use yet flexible design.

Installation

npm install react-fcm-notification

Usage

1. Firebase Initialization

Create a Firebase project and obtain the required settings. Then initialize the Messaging instance from Firebase.

// src/firebase.ts
import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging";

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID",
};

const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);

Alternatively, modularize the initialization as follows:

import { FirebaseApp, initializeApp } from "firebase/app";
import { getMessaging, Messaging } from "firebase/messaging";

let app: FirebaseApp;
let messaging: Messaging;

export const fcmEndpointUrl = `https://fcm.googleapis.com/v1/projects/__PROJECT_ID__/messages:send`

export const loadApp = (): FirebaseApp|null => {
  if ('serviceWorker' in navigator) {
    if (!app) {
      app = initializeApp({
        apiKey: "YOUR_API_KEY",
        authDomain: "YOUR_AUTH_DOMAIN",
        projectId: "YOUR_PROJECT_ID",
        storageBucket: "YOUR_STORAGE_BUCKET",
        messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
        appId: "YOUR_APP_ID",
      })
    }
  }

  return app || null
}

export const loadMessaging = (): Messaging|null => {
  if ('serviceWorker' in navigator) {
    if (!messaging) {
      const app = loadApp()
      if (app) {
        messaging = getMessaging(app)
      }
    }
  }

  return messaging || null
}

interface UseFirebase {
  app: FirebaseApp | null
  messaging: Messaging | null
}

export const useFirebase = (): UseFirebase => {
  const app = useMemo(() => loadApp(), [])
  const messaging = useMemo(() => loadMessaging(), [])
  return { app, messaging }
}

2. Using the Component

Use the Notification component to implement the notification feature.

import React from "react";
import { Notification } from "react-fcm-notification";

const App: React.FC = () => {
  const { messaging } = useFirebase()

  if (!messaging) {
    return <p>Your browser does not support notifications.</p>;
  }

  return (
    <Notification
      messaging={messaging}
      vapidKey="YOUR_PUBLIC_VAPID_KEY"
      postRequest={(token) => /* api.registerDevice(token) */}
      postRemove={(token) => /* api.unregisterDevice(token) */}
    >
      {({ loading, isTokenActive, toggle }) => (
        <div>
          <p>Notifications are currently {loading ? "loading..." : (isTokenActive ? "enabled" : "disabled")}.</p>
          <button onClick={toggle}>
            {isTokenActive ? "Disable Notifications" : "Enable Notifications"}
          </button>
        </div>
      )}
    </Notification>
  );
};

export default App;

API

<Notification />

PropertyTypeRequiredDescription
messagingMessagingRequiredThe Firebase Messaging instance.
vapidKeystringRequiredThe VAPID key required to obtain an FCM token.
postRequest(token: string) => anyOptionalCallback triggered when a token is retrieved.
postRemove(token: string) => anyOptionalCallback triggered when a token is removed.
children({ loading, isTokenActive, toggle }) => React.ReactNodeRequiredA render function receiving the token state and a toggle function.

useFcm

A custom hook for managing FCM tokens.

const { loading, isTokenActive, requestToken, removeToken } = useFcm({
  messaging,
  vapidKey,
  postRequest,
  postRemove,
});
Return ValueTypeDescription
loadingbooleanIndicates whether token request is currently in progress.
isTokenActivebooleanIndicates if the token is active.
requestToken() => anyFunction to request a token.
removeToken() => anyFunction to remove a token.

useNotification

A custom hook for managing notification permissions.

const { loading, permission, requestPermission } = useNotification();
Return ValueTypeDescription
loadingbooleanIndicates whether a notification permission request is currently in progress.
permissionNotificationPermissionRepresents the current permission status for notifications (e.g., "granted", "denied", "default").
requestPermission() => Promise<NotificationPermission>Function to request notification permission from the user.

Author

@shinosaki

License

MIT License

Keywords

react

FAQs

Package last updated on 29 Dec 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts