I have built an app with react js using expo. I am trying to schedule a local notification. The notification ID is getting generated. But it is triggered immediately, not being scheduled. I logged all the scheduled notifications using const scheduled = await Notifications.getAllScheduledNotificationsAsync();but the scheduled array is returning []. I am calling this scheduleDailyNotification() function after successful signup. I have built my app in developer mode. And still having this problem. Can anyone help?
import * as Notifications from 'expo-notifications';
import { Alert, Platform } from 'react-native';
import Constants from "expo-constants";
import * as Device from 'expo-device';
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true, // β
Ensures the notification is displayed
shouldPlaySound: true, // β
Enables sound
shouldSetBadge: false, // β No badge update
}),
});
async function createNotificationChannel() {
if (Platform.OS === 'android') {
await Notifications.setNotificationChannelAsync('default', {
name: 'Default Channel',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
}
// β
Request Notification Permission and return boolean status
async function requestNotificationPermission() {
const { status } = await Notifications.getPermissionsAsync();
Alert.alert("π Initial Permission Status", status); // β
Show initial permission status
console.log("π Initial Permission Status", status);
if (status !== 'granted') {
const { status: newStatus } = await Notifications.requestPermissionsAsync();
Alert.alert("π’ New Permission Status", newStatus); // β
Show new permission status
console.log("π’ New Permission Status", newStatus);
if (newStatus !== 'granted') {
Alert.alert('β Permission Denied', 'Notifications are disabled.');
return false;
}
}
return true;
}
// β
Schedule Daily Notification
async function scheduleDailyNotification() {
await createNotificationChannel();
await Notifications.cancelAllScheduledNotificationsAsync(); // Clears old schedules to prevent duplicates
await Notifications.scheduleNotificationAsync({
content: {
title: "Daily Reminder",
body: "It is a scheduled notification!",
sound: "default",
priority: Notifications.AndroidNotificationPriority.MAX,
},
trigger: {
hour: 20, // β
8:10 PM (24-hour format)
minute: 10,
repeats: true, // π Repeat every day
useUTC: false,
},
});
// β
Fetch all scheduled notifications to verify it's scheduled
const scheduled = await Notifications.getAllScheduledNotificationsAsync();
console.log("π
Scheduled Notifications:", scheduled);
if (scheduled.length > 0) {
Alert.alert("β
Notification Scheduled", `Next reminder at 3:00 PM`);
} else {
Alert.alert("β No Notifications Scheduled", "Something went wrong.");
}
}
export { scheduleDailyNotification };