question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How use it with redux?

See original GitHub issue

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)
			}
		})
	}
}

captura de pantalla 2016-11-10 a la s 16 52 37

Is this error appearing because redux is an internal javascript structure and “PushNotification.configure” is on a native level?

Thanks!

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:1
  • Comments:8

github_iconTop GitHub Comments

8reactions
saalihoucommented, Nov 29, 2016

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 }

1reaction
Ajmal0197commented, Oct 13, 2020

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
};
Read more comments on GitHub >

github_iconTop Results From Across the Web

Getting Started with Redux
The recommended way to start new apps with React and Redux is by using the official Redux+JS template or Redux+TS template for Create...
Read more >
How to use Redux in ReactJS with real-life examples
How to use Redux in ReactJS with real-life examples · import { Provider } from "react-redux"; import configureStore from "store"; · ReactDOM.
Read more >
Understanding Redux: A tutorial with examples
Simply put, Redux is used to maintain and update data across your applications for multiple components to share, all while remaining independent ...
Read more >
How to Use Redux With React: A Step By Step Guide - Medium
In Redux, there is one source of truth: the store · It's not specific to React. You can use it with other frameworks...
Read more >
React With Redux Tutorial: Learn the Basics [Updated]
Redux is a predictable state container for JavaScript applications. It helps you write apps that behave consistently, run in different ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found