How to set an interval in expo notifications?

57 Views Asked by At

What I want to achieve is if the priority is set to First Priority, I want to sent the notification 30 minutes before the task starts and repeat it every 5 minutes until start time. if the priority is set to Second Priority, I want to send the notification 15 minutes before the task starts and repeat it every 5 minutes just like first priority. if the priority is set to Normal Priority, I want to send the notification 5 minutes before the task start and not repeat it. So far, what I've done is I've managed to send the notification at the correct time but I'm struggling to repeat it like I want. Please help.

This is what my code looks like right now.

export async function scheduleNotificationBeforeTask(startTime, taskData, priority) {
  try {
    const notificationContent = {
      title: `${priority === 'First Priority' ? 'Priority ' : ''}` + "Task Reminder",
      body: `Your task "${taskData}" is starting soon`,
      data: { taskData },
    };

    const scheduledNotifications = await Notifications.getAllScheduledNotificationsAsync();
    const notificationsToCancel = scheduledNotifications.filter(
      (notification) => notification.content.data.taskData === taskData
    );

    notificationsToCancel.forEach(async (notification) => {
      await Notifications.cancelScheduledNotificationAsync(notification.identifier);
    });

    if (priority === 'Normal Priority') {
      const notificationTime = Moment(startTime, 'hh:mm A').subtract(5, 'minutes');
      await Notifications.scheduleNotificationAsync({
        content: notificationContent,
        trigger: {
          date: notificationTime.toDate(),
        },
      });
    } else if (priority === 'Second Priority' || priority === 'First Priority') {
      const notificationTime = Moment(startTime, 'hh:mm A').subtract(
        priority === 'First Priority' ? 30 : 15,
        'minutes'
      );
      
      const totalRepetitions = priority === 'First Priority' ? 6 : 3;

      await Notifications.scheduleNotificationAsync({
        content: notificationContent,
        trigger: {
          seconds: 300,
          repeats: true,
          date : notificationTime.toDate()
        },
      });
    }
  } catch (error) {
    console.error('Error scheduling notification:', error);
  }
}
0

There are 0 best solutions below