I have a reducer that updates my "badge" in application design so i have this
import PushNotification from 'react-native-push-notification'
class Main extends Component{
construct(){}
PushNotification.configure({
onRegister: function(token) {
AsyncStorage.getItem('deviceToken',(err,localToken) => {
if(localToken === null){
fetch("myreques",{
method : 'POST'
}).then( response => response.json())
.then( posts => {
AsyncStorage.setItem('deviceToken', token.token);
})
}
})
},
onNotification: function(notification) {
AsyncStorage.getItem('pendingNotifications',(err,data) => {
if(null != data){
data = JSON.parse(data)
data.push({
id : parseInt(notification.id),
viewed : false
})
AsyncStorage.setItem('pendingNotifications',JSON.stringify(data))
}else{
let data = [{
id : notification.id,
viewed : false
}]
AsyncStorage.setItem('pendingNotifications',JSON.stringify(data))
}
//this._updateBagde() <-- this line make app crashes
if(Platform.OS === 'ios'){
PushNotification.setApplicationIconBadgeNumber(parseInt(notification.badge))
}
})
this._updateBagde();
},
// ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
senderID: "MINE",
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
requestPermissions: true,
});
PushNotification.requestPermissions("MINE");
this._updateBagde()
}
_updateBagde(){
AsyncStorage.getItem('pendingNotifications',(err,notViewed) => {
if(notViewed != null){
//traer las que no han sido vistas
let parsedNotifications = JSON.parse(notViewed)
let filtered = parsedNotifications.filter((item) => {
if(!item.viewed){
return item
}
})
if(Platform.OS === 'ios'){
PushNotification.setApplicationIconBadgeNumber(parseInt(filtered.length))
}
//console.log(filtered,'badge')
this.props.updateBadge(filtered.length)
}
})
}
}

Is this error appearing because redux is an internal javascript structure and "PushNotification.configure" is on a native level?
Thanks!
No. You just made a typo in the method name.
You wrote:
this._updateBagde()
It should be:
this._updateBadge()
@saalihou but my function from component names _updateBagde()
I just pasted your code in my IDE because I had trouble reading it on github. There apparently are syntax errors PushNotification.configure(...) should be inside a method or outside the class. It cannot float freely in the class declaration.
@saalihou yes of course, PushNotification.configure(...) is inside of componentWillMount now, in the example is not.... sorry about that
Oh, I just saw your problem. The onNotification callback you gave is a function. Thus, the this keyword refers to another object, not your component. In order to solve it, you can declare the onNotification callback as a lambda, like this:
onNotification: () => { // your logic here }
@saalihou WOOOOOOOOOOOOOOOOWWWWW man that is truth! thanks a lot, i will do it! i MEGA LOVE U
@cinder92 You are welcome. Do not forget to close the issue ;). Happy React'ing!
USING REDUX WITH NOTIFICATION HANDLER
-->App.js
import { Configure } from './config/NotificationHandler'
const App = () => {
return (
<SafeAreaProvider>
<StatusBar barStyle="dark-content" hidden={false} backgroundColor="#1A1A1A" translucent={true} />
<Provider store={store} >
<Configure />
<View style={{ flex: 1 }} >
<AuthLoading />
</View>
</Provider>
</SafeAreaProvider>
)
}
export default App;
-->Notificationhandler.js
import React, { useEffect } from 'react';
import PushNotificationIOS from "@react-native-community/push-notification-ios";
import PushNotification from 'react-native-push-notification';
import AsyncStorage from '@react-native-community/async-storage';
import NavigationService from '../routing/NavigationService'
import { useDispatch, useSelector, shallowEqual } from 'react-redux';
const Configure = () => {
const { activeProject } = useSelector(state => ({
activeProject: state.homeReducer.activeProject,
}), shallowEqual);
const dispatch = useDispatch();
// Must be outside of any component LifeCycle (such as `componentDidMount`).
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function (token) {
console.log("RNPNonRegistertoken:", token);
AsyncStorage.setItem('fcmToken', token.token);
},
// (required) Called when a remote is received or opened, or local notification is opened
onNotification: function (notification) {
console.log("NOTIFICATION:", notification, activeProject);
// process the notification
if (notification?.data?.url) {
NavigationService.navigate('PDFScreen', { Key: 'URL', urlForPDF: notification.data.url })
} else if (notification.id > 0 && notification.id < 7 && global.notifNavVar) {
global.localPushID = notification.id
NavigationService.navigate('AllTimersButton')
} else if (notification.id == 7 && global.notifNavVarP) {
NavigationService.navigate('ProjectDetail')
}
// (required) Called when a remote is received or opened, or local notification is opened
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// (optional) Called when Registered Action is pressed and invokeApp is false, if true onNotification will be called (Android)
onAction: function (notification) {
console.log("ACTION:", notification.action);
console.log("NOTIFICATION:", notification);
// process the action
},
// (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
// onRegistrationError: function(err) {
// console.error(err.message, err);
// },
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true,
},
largeIcon: "ic_launcher",
smallIcon: "ic_launcher",
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
* - if you are not using remote notification or do not have Firebase installed, use this:
* requestPermissions: Platform.OS === 'ios'
*/
});
return null
};
const LocalNotificationSchedule = (id, afterSec, message = '', title = '') => {
PushNotification.localNotificationSchedule({
//... You can use all the options from localNotifications
id: id + '',
title,
message, // (required)
date: new Date(Date.now() + afterSec * 1000), // in n secs
playSound: true,
// soundName: 'local_notification_custom_tone.mp3',
vibrate: true,
vibration: 180000,
allowWhileIdle: true,
visibility: "public",
// soundName: 'default',
showWhen: true,
usesChronometer: true,
ignoreInForeground: false,
priority: "max",
})
}
const CancelLocalNotifications = (id) => {
PushNotification.cancelLocalNotifications({ id: id + '' })
}
// const LocalNotification = () => {
// PushNotification.localNotification({
// id: 0, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
// autoCancel: true,
// bigText: 'This is local notification demo in React Native app. Only shown, when expanded.',
// subText: 'Local Notification Demo',
// title: 'Local Notification Title',
// message: 'Expand me to see more',
// vibrate: true,
// vibration: 300,
// playSound: true,
// soundName:'default',
// actions: '["Yes", "No"]'
// })
// }
export {
Configure,
LocalNotificationSchedule,
CancelLocalNotifications,
// LocalNotification
};
Most helpful comment
Oh, I just saw your problem. The onNotification callback you gave is a
function. Thus, thethiskeyword refers to another object, not your component. In order to solve it, you can declare the onNotification callback as a lambda, like this:onNotification: () => { // your logic here }