I execute following code in my useEffect hook:
const requestNotificationPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
{
title: 'Notification Permission',
message: 'Allow the app to send you notifications',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('Notification permission granted');
} else {
console.log('Notification permission denied');
}
} catch (err) {
console.warn(err);
}
};
useEffect(() => {
AppState.addEventListener('change', (state) => {
if (state === 'active') {
fetchData();
}
});
requestNotificationPermission();
fetchData();
getList();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
But it acts really weird. Without asking for the permission it works perfectly fine, but when using it the fetchData() function execute multiple times. And also the permission gets automatically denied without a popup or any ask of the permission. Then my app get’s bugged by displaying an array multiple times even when I only want do display once.
I don’t know what the problem is and also looked up in the internet, but no one seems to have this problem. If I try to send a push notification via react native using PushNotification.localNotification it works, but I honestly don’t know if this has something to do with my problem. I also included <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
in my AndroidManifes.xml and my API version is 31 or higher. So maybe someone with knowledge could help me.
2
Answers
If anyone needs a workaround for this issue, what I ended up doing was requesting the user to allow the notifications on the settings app. I used Linking for that, following the documentation https://reactnative.dev/docs/linking
You can either open the settings page of the app with
Or you can open the notification settings for your app useing sendIntent instead of openSettings
These samples work for android, for what I get from the documentation sendIntent() might not be available for ios.
Hope this helps.
Still new to React Native myself but I was having issues with getting the notification permission popup as well.
Found that I needed to make the following change:
android/build.gradle
I believe since Android only requires notification permissions with API 33+, that API needs to be targeted. I was also at API 31 previously.