Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear Previous Expo Push Notifications

I have my app in Expo pushing a notification when somebody sends a message, but if that person sends multiple messages a second notification is pushed.

Is there anything I can do to clear the previous notification, or simply update the notification instead of adding a second notification to the list?

Basically I need to force an override or dismiss previous notifications.

The approach I was hoping to use was to add a listener which cleared notifications before appending, but it seems that this only works when the app is in the foreground.

Is there a recommended approach to this currently?

like image 788
SeanVDH Avatar asked Nov 27 '22 02:11

SeanVDH


1 Answers

You can clear any or all previous notifications in expo-notifications. Your question is not clear but I am guessing you want to clear all previous notification if new notification is received. You have to spot the best place when to clear notifications on your code. But here are some tips (use the following code in the useEffect hook) -

// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
responseListener.current =
  Notifications.addNotificationResponseReceivedListener((response) => {
    // DISMISS ALL NOTIFICATION AFTER INTERACTION
    Notifications.dismissAllNotificationsAsync();
  });

If you want to dismiss specific notification in that case, use dismissNotificationAsync(identifier: string): Promise method.

Just in case, if you want to dismiss all notifications when receiving a new one while the app is foregrounded (use the following code in the useEffect hook).

// This listener is fired whenever a notification is received while the app is foregrounded
notificationListener.current =
  Notifications.addNotificationReceivedListener((notification) => {
    // setNotification(notification);
    // DISMISS ALL NOTIFICATION UPON RECEIVING NOTIFICATION WHILE IN FOREGROUND
    Notifications.dismissAllNotificationsAsync();
  });

You can use Notifications.dismissAllNotificationsAsync() method or dismissNotificationAsync(identifier: string): Promise method anywhere you like but you need to spot where to best use them.

like image 199
hafij Avatar answered Dec 05 '22 19:12

hafij