I have a problem regarding the following code sample:
Notifications.setNotificationHandler({//makes sure notification is displayed even when app is open, nothing else
handleNotification: async (notification) => {
//const value = await AsyncStorage.getItem('presetlanguage');
//console.log("ASYNC STORAGE LANGUAGE FROM OUTSIDEEEE: ", value)
//if(notification.request.content.body == "You received a new letter from a PigeonBuddy!"){
// console.log("hat geklappt")
//}
return{
shouldShowAlert: true
};
}
});
const MainScreen = props => {
const dispatch = useDispatch();
var chosenLanguage = useSelector(state => state.myLanguage.myLanguage); ...........
The setNotificationHandler
is responsible for handling incoming notifications and therefore I want to filter my incoming notifications. For example, depending on which screen I am on, I want to either display the notification or not display it. The problem however is, I have neither access to my navigation state nor to my redux states because this handling of the notifications happens outside the default screen main function which covers all variables and which also uses props through navigations. It is forbidden to call redux hooks there and also I have no access to my navigation state because I have no access to my props variable which I get through navigation.
How can I display my notifications then depending on which screen I am on? How are companies like Facebook doing it? If you're on a chat screen you don't get notifications but if you are outside a notification "New message received from ..." is displayed.
You can export a navigation ref
export const navRef = React.createRef();
const App = () => {
return (
<NavigationContainer ref={navRef}>
...
</NavigationContainer>
);
};
and use it to get the screen you are in, inside the setNotificationHandler
const currentRouteName = navRef.current.getCurrentRoute().name;
can use similar code. this code is for react-navigation v6
Edited
for React-navigation v4 create a reactRef that keeps track of current screen utilising the onNavigationStateChange.
export const currentScreenRef = React.createRef('Splash');
function getActiveRouteName(navigationState) {
if (!navigationState) {
return null;
}
const route = navigationState.routes[navigationState.index];
if (route.routes) {
return getActiveRouteName(route);
}
return route.routeName;
}
const App = () => {
return (
<NavigationContainer
onNavigationStateChange={(prevState, currentState) => {
const currentRouteName = getActiveRouteName(currentState);
currentScreenRef.current = currentRouteName;
}}
>
...
</NavigationContainer>
);
};
so will be able to call it as
const currentRouteName = currentScreenRef.current;
NB: not tested as do not have any projects running V4. If not working or needs edit, add a comment