'Expo Push Notifications - Disable notifications in a specific screen
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?
Solution 1:[1]
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.
Solution 2:[2]
This code works for me:
useEffect(() => {
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: false,
shouldPlaySound: false,
shouldSetBadge: false,
iosDisplayInForeground: false
})
});
}, [])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Grant Clark |
Solution 2 | Scott |