Skip to content

Instantly share code, notes, and snippets.

@helenaford
Last active March 20, 2024 09:16
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save helenaford/97e9bcdc587b333745f98ea0722bbce6 to your computer and use it in GitHub Desktop.
Save helenaford/97e9bcdc587b333745f98ea0722bbce6 to your computer and use it in GitHub Desktop.
useNotificationService
import { useNotificationService } from './hooks';
function App() {
useNotificationService();
...
}
import React, { useEffect, useState, useRef } from 'react';
import { AppState } from 'react-native';
import { useNotifs } from './notifications';
import { fcm } from '../utils';
export const useNotificationService = () => {
const listenersRef = useRef();
const notifs = useNotifs();
useEffect(() => {
async function callInitialise() {
// initialise fcm and listeners
listenersRef.current = await initialise();
}
callInitialise();
return function cleanup() {
// clear listeners
fcm.clearListeners(listenersRef.current);
};
/* https://github.com/facebook/react/issues/15865 */
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
function handleNotifPress(notification, details) {
notifs.updateNotif(notification);
}
function handleNotificationReceived(notification) {
notifs.updateNotif(notification);
}
async function initialise() {
// attempt to get token and create listener
return fcm.attemptToGetToken().then(() => {
// Build a channel
fcm.createAndroidChannel();
fcm.getInitialNotif();
fcm.getScheduledNotifications().then(notifications => {
notifs.updateNotifs(notifications);
});
fcm.getDeliveredNotifications().then(notifications => {
notifs.updateNotifs(notifications);
});
return fcm.createNotificationListeners(...);
});
}
return null;
};
export default { useNotificationService };
import { AsyncStorage } from 'react-native';
import firebase from 'react-native-firebase';
import moment from 'moment';
const CHANNEL_NAME = 'test-channel';
const getToken = async () => {
let fcmToken = await AsyncStorage.getItem('fcmToken');
if (!fcmToken) {
fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
await AsyncStorage.setItem('fcmToken', fcmToken);
}
}
return fcmToken;
};
const requestPermission = async () =>
await firebase.messaging().requestPermission();
export const attemptToGetToken = async () =>
requestPermission()
.then(() => getToken())
.catch(() => {});
function buildNotification(type, id) {...}
export function displayNotification(type = 'NOTIFICATION', id) {
const notification = buildNotification(type, id);
// Display the notification
firebase.notifications().displayNotification(notification);
return notification;
}
export function scheduleLocalNotification(type, delay, id) {...}
function getDeliveredNotifications() {
return firebase.notifications().getDeliveredNotifications();
}
function getScheduledNotifications() {
return firebase.notifications().getScheduledNotifications();
}
function cancelAllNotifications() {
return firebase.notifications().cancelAllNotifications();
}
export const createNotificationListeners = () => {
const onIncoming = firebase.notifications().onNotification(notification => {
console.log(
'MyNotifsPipeline onIncoming',
notification
);
notification.android.setChannelId(CHANNEL_NAME);
return firebase.notifications().displayNotification(notification);
});
const onDisplayed = firebase
.notifications()
.onNotificationDisplayed((notification: Notification) => {
console.log('MyNotifsPipeline onNotificationDisplayed', notification);
});
const onOpened = firebase
.notifications()
.onNotificationOpened(notificationOpen => {
const notif = notificationOpen.notification;
// does not work when app was terminated
console.log('MyNotifsPipeline onNotificationOpened', notif);
});
const onTokenRefresh = firebase.messaging().onTokenRefresh(token => {
// TODO: handle new token. e.g. update token on server
});
const onMessage = firebase.messaging().onMessage(message => {
console.log('MyNotifsPipeline onMessage', message, message.sentTime);
});
// optional -> subscribe device to topic
firebase.messaging().subscribeToTopic('main-topic');
return { onIncoming, onOpened, onTokenRefresh, onMessage, onDisplayed };
};
const createAndroidChannel = () => {
const androidChannel = new firebase.notifications.Android.Channel(
CHANNEL_NAME,
'Test Channel',
firebase.notifications.Android.Importance.Max,
).setDescription('My apps test channel');
firebase.notifications().android.createChannel(androidChannel);
};
const getInitialNotif = (}) => {
firebase
.notifications()
.getInitialNotification()
.then(notificationOpen => {
if (notificationOpen) {
// Get information about the notification that opened the app
}
});
};
function removeAllDeliveredNotifications() {
return firebase.notifications().removeAllDeliveredNotifications();
}
const clearListeners = ({
onIncoming,
onOpened,
onTokenRefresh,
onMessage,
onDisplayed,
}) => {
onIncoming();
onOpened();
onTokenRefresh();
onMessage();
onDisplayed();
};
export const fcm = {
attemptToGetToken,
createNotificationListeners,
createAndroidChannel,
getInitialNotif,
clearListeners,
displayNotification,
scheduleLocalNotification,
getDeliveredNotifications,
getScheduledNotifications,
removeAllDeliveredNotifications,
cancelAllNotifications,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment