I’m trying to use Expo Notifications with Redux Toolkit. This is the function that handles the logic of the Notification permissions.
export const requestNotificationPermission = () => async (dispatch, getState) => {
dispatch(requestPermissionPending());
try {
const { permissionStatus } = getState().notification;
if (permissionStatus === "granted") {
console.log("Notification permission already granted");
return;
}
if (permissionStatus === "denied") {
console.log("Notification permission already denied");
return;
}
if (Platform.OS !== "web") {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
if (existingStatus === "denied") {
console.log("Notification permission already denied");
return;
}
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
console.log("Notification permission not granted");
dispatch(
requestPermissionError("Permission for notifications denied")
);
return;
}
dispatch(updatePermissionStatus(finalStatus));
if (finalStatus === "granted") {
const { token } = await Notifications.getExpoPushTokenAsync();
console.log("Token: ", token); <--- HERE
dispatch(requestPermissionSuccess({ expoPushToken: token }));
const user_id = getState().auth.user_id;
try {
// Save the user_id and token to the database
await storePushToken(user_id, token);
console.log("Token saved to the database successfully!");
} catch (error) {
console.log("Error saving token to the database:", error);
}
}
}
} catch (error) {
dispatch(requestPermissionError(error.message));
}
};
First, I await the existingStatus to get the permission from Notifications.getPermissionsAsync()
, and it is returning granted. That makes that the granted if
statement runs, but the console.log
(and the forward calls) return that the token is undefined
. Why could that be??