Skip to content

Instantly share code, notes, and snippets.

@mirsahib
Created May 30, 2024 06:35
Show Gist options
  • Save mirsahib/66850b598d8e95c2c90efbea65ea9731 to your computer and use it in GitHub Desktop.
Save mirsahib/66850b598d8e95c2c90efbea65ea9731 to your computer and use it in GitHub Desktop.
import React, {
createContext,
useContext,
useEffect,
useRef,
useState,
} from 'react';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';
import { Platform } from 'react-native'
// @ts-ignore
const FirebaseNotificationContext = createContext();
/**
* Returns the FirebaseNotification context from the nearest FirebaseNotificationProvider in the component tree.
*
* @return {Object} The FirebaseNotification context object.
* @throws {Error} If used outside of a FirebaseNotificationProvider.
*/
export const useFirebaseNotificationContext = () => {
const context = useContext(FirebaseNotificationContext);
if (!context) {
throw new Error(
'FirebaseNotificationContext must be used within a FirebaseNotificationProvider',
);
}
return context;
};
export const FirebaseNotificationProvider = ({ children }) => {
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
}),
});
const [expoPushToken, setExpoPushToken] = useState(undefined);
const [notification, setNotification] = useState(undefined);
const notificationListener = useRef();
const responseListener = useRef();
const registerForPushNotificationsAsync = async () => {
let token;
if (Device.isDevice) {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification");
return;
}
token = await Notifications.getExpoPushTokenAsync({
projectId: Constants?.expoConfig?.extra?.eas?.projectId ?? Constants?.easConfig?.projectId;,
});
} else {
alert("Must be using a physical device for Push notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
return token;
}
useEffect(() => {
registerForPushNotificationsAsync().then((token) => {
// @ts-ignore
setExpoPushToken(token.data);
}).catch((error) => {
console.log("πŸš€ ~ registerForPushNotificationsAsync ~ error:", error)
});
// getToken()
// @ts-ignore
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
console.log("πŸš€ ~ Notifications.addNotificationReceivedListener ~ notification:", notification)
setNotification(notification);
});
// @ts-ignore
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
console.log("πŸš€ ~ Notifications.addNotificationResponseReceivedListener ~ response:", response)
});
return () => {
Notifications.removeNotificationSubscription(notificationListener.current);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
return (
<FirebaseNotificationContext.Provider
value={{
expoPushToken,
notification,
}}
>
{children}
</FirebaseNotificationContext.Provider>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment