Skip to content

Instantly share code, notes, and snippets.

@IgorDePaula
Created May 1, 2026 22:47
Show Gist options
  • Select an option

  • Save IgorDePaula/0f0ffddfd0266227574c3063e40acc56 to your computer and use it in GitHub Desktop.

Select an option

Save IgorDePaula/0f0ffddfd0266227574c3063e40acc56 to your computer and use it in GitHub Desktop.
import { useState, useEffect, useRef } from "react";
import * as Device from "expo-device";
import * as Notifications from "expo-notifications";
import Constants from "expo-constants";
import { Platform } from "react-native";
export const usePushNotifications = () => {
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldPlaySound: true,
shouldShowAlert: true,
shouldSetBadge: true,
}),
});
const [expoPushToken, setExpoPushToken] = useState();
const [notification, setNotification] = useState();
const notificationListener = useRef();
const responseListener = useRef();
async function registerForPushNotificationsAsync() {
let token;
if (Device.isDevice) {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync({
android:{
importance: 1,
interruptionFilter: 1
}
});
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,
});
} else {
alert("Must be using a physical device for Push notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("teste-igor", {
name: "teste-igor",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 100, 250],
lightColor: "#FF231F7C",
});
}
return token;
}
useEffect(() => {
registerForPushNotificationsAsync().then((token) => {
setExpoPushToken(token);
});
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
setNotification(notification);
});
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
console.log(response);
});
return () => {
Notifications.removeNotificationSubscription(
notificationListener.current
);
Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
return {
expoPushToken,
notification,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment