Expo Push Notifications - Disable notifications in a specific screen

Viewed 945

How can I disable showing notifications in my Expo app when the user is in a specific screen?

I am currently designing a chat screen, and I want to disable push notifications when the user is inside it.

Currently, I have implemented the following methods in my PushNotifications module:

export function setNotificationHandler(handler) {
  ExpoNotifications.setNotificationHandler(handler);
}

export function hidePushNotifications() {
  setNotificationHandler({
    handleNotification: async () => ({
      shouldShowAlert: false,
      shouldPlaySound: false,
      shouldSetBadge: false,
    }),
  });
}

export function unhidePushNotifications() {
  setNotificationHandler({
    handleNotification: async () => ({
      shouldShowAlert: true,
      shouldPlaySound: true,
      shouldSetBadge: true,
    }),
  });
}

And in my Chat screen, in a useEffect, I am doing:

useEffect(() => {
  // Do not show push notifications when the user is inside this screen
  hidePushNotifications();

  return () => {
    // When unmounted, unhide push notifications
    unhidePushNotifications();
  };
}, []);

For me, this has sense, as I am "hiding" push notifications when the user enters the chat screen, and "unhiding" them when he leaves.

But for some reasons, the notifications still appear inside the chat screen. Why?

How can I solve this issue?

3 Answers

Can't be 100% sure without knowing more about the structure of your app, but you should verify that your screen is unmounting when you expect it to with some simple console.log statements or something similar.

If your screen is not unmounting when you expected it to and you're using something like React Navigation to handle your screens, you should look over the Navigation Lifecycle to address the issue.

This is obviously making some assumptions about your issue, but hopefully that helps.

This code works for me:

  useEffect(() => {
    Notifications.setNotificationHandler({
      handleNotification: async () => ({
        shouldShowAlert: false,
        shouldPlaySound: false,
        shouldSetBadge: false,
        iosDisplayInForeground: false
      })
    });
  }, [])

You can use the useFocusEffect hook to know when the screen unmounts.

  useFocusEffect(
    useCallback(() => {
     Notifications.setNotificationHandler({
      handleNotification: async () => ({
        shouldShowAlert: true,
        shouldPlaySound: false,
        shouldSetBadge: false,
      }),
    });
    return () => {
       Notifications.setNotificationHandler({
        handleNotification: async () => ({
          shouldShowAlert: false,
          shouldPlaySound: false,
          shouldSetBadge: false,
      }),
     });
    };
   }, [])
  );

Related