Skip to content

Instantly share code, notes, and snippets.

@KROSF
Created March 5, 2022 20:54
Show Gist options
  • Save KROSF/5a24992829deff02cdbc3f23e88e6af4 to your computer and use it in GitHub Desktop.
Save KROSF/5a24992829deff02cdbc3f23e88e6af4 to your computer and use it in GitHub Desktop.
Firebase Push Notifications
import messaging, {
FirebaseMessagingTypes,
} from '@react-native-firebase/messaging';
export const onMessageReceived = async (
message: FirebaseMessagingTypes.RemoteMessage,
) => {
// handle messages here
};
export const setupPushNotifications = () => {
messaging().setBackgroundMessageHandler(onMessageReceived);
};
import messaging from '@react-native-firebase/messaging';
import { requestPushNotificationPermission } from './permission';
import { onMessageReceived } from './handler';
const getFcmToken = async () => {
try {
const token = await messaging().getToken();
return token;
} catch (error) {
return undefined;
}
};
const useForegroundNotificationEffect = () => {
useEffect(() => {
messaging().onMessage(onMessageReceived);
}, []);
};
const useFCMTokenEffect = () => {
const updateFCMToken = useCallback(async () => {
const notificationToken = await getFcmToken();
const hasPermission = await requestPushNotificationPermission();
const saved = { notificationToken: '' }; // Get from your server
if (notificationToken === saved.notificationToken || !hasPermission) return;
await updateTokenOnYourServer({ notificationToken });
}, []);
useEffect(() => {
updateFCMToken();
}, [updateFCMToken]);
};
const useForegroundNotificationEffect = () => {
useEffect(() => {
messaging().onMessage(onMessageReceived);
}, []);
};
export const usePushNotificationEffect = () => {
useFCMTokenEffect();
useForegroundNotificationEffect();
};
import messaging from '@react-native-firebase/messaging';
export const requestPushNotificationPermission = async () => {
try {
const status = await messaging().requestPermission();
return (
status === messaging.AuthorizationStatus.AUTHORIZED ||
status === messaging.AuthorizationStatus.PROVISIONAL
);
} catch {
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment