React Native error Invariant Violation: `new NativeEventEmitter()` requires a non-null argument. IOS app showing white screen
Asked Answered
H

0

7

When i run the app build is successful and when the app is installed on the ios simulator it shows white screen. Using NVM for node node 16.14.2 xcode 14.2 macbook rpo 2017 firebase firestore,push notifications from @react-native-firebase

stack trace

  BUNDLE  ./index.js 

 ERROR  Invariant Violation: `new NativeEventEmitter()` requires a non-null argument.
 ERROR  Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
      This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
 ERROR  Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
      This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
package.json file
{
  "name": "digitvl_app",
  "version": "0.0.1",
  "private": true,
  "rnpm":{
    "assets":["./assets/fonts"]
    
  },
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-firebase/app": "^16.5.0",
    "@react-native-firebase/auth": "^16.5.0",
    "@react-native-firebase/firestore": "^16.5.0",
    "@react-native-firebase/messaging": "^16.5.0",
    "@react-navigation/native": "^6.1.1",
    "@react-navigation/native-stack": "^6.9.7",
    "firebase": "^9.15.0",
    "react": "17.0.2",
    "react-native": "0.68.2",
    "react-native-paper": "^5.1.3",
    "react-native-push-notification": "^8.1.1",
    "react-native-safe-area-context": "^4.4.1",
    "react-native-screens": "^3.18.2"
  },
  "devDependencies": {
    "@babel/core": "^7.20.12",
    "@babel/runtime": "^7.20.7",
    "@react-native-community/eslint-config": "^3.2.0",
    "babel-jest": "^29.3.1",
    "eslint": "^8.31.0",
    "jest": "^29.3.1",
    "metro-react-native-babel-preset": "^0.73.7",
    "react-test-renderer": "17.0.2"
  },
  "jest": {
    "preset": "react-native"
  }
}
metro.config.js
module.exports = {
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: true,
      },
    }),
  },
};
const { getDefaultConfig } = require("metro-config");
const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues();
exports.resolver = {
  ...defaultResolver,
  sourceExts: [
    ...defaultResolver.sourceExts,
    "cjs",
  ],
};
App.js
import React, {useEffect, useState} from 'react';
import {StyleSheet, Text, View, Linking, Platform} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import HomeScreen from './screens/HomeScreen';
import LoginScreen from './screens/LoginScreen';
import messaging from '@react-native-firebase/messaging';
import SendNotificationScreen from './screens/SendNotificationScreen';
import PushNotification, {Importance} from 'react-native-push-notification';
import firestore from '@react-native-firebase/firestore';
import auth from '@react-native-firebase/auth'
const Stack = createNativeStackNavigator();
// import NotificationRedirector from './src/Helper/NotificationRedirector/NotificationRedirector';

// const requestUserPermission = async function requestUserPermission() {
//   const authStatus = await messaging().requestPermission();
//   const enabled =
//     authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
//     authStatus === messaging.AuthorizationStatus.PROVISIONAL;

//   if (enabled) {
//     console.log('Authorization status:', authStatus);
//   }
// }

export default function App() {
  const [state,setState] = useState({})
  const requestPermission = async () => {
    const oldToken = await messaging().getToken();
    console.log('oldToken:' + oldToken);
    if(auth().currentUser){
      firestore().collection("userToken").doc(auth().currentUser.uid).update({
        token:oldToken
      })
    }
    
    messaging().onTokenRefresh(token => {
      console.log('tokenRefresh:' + token);
      console.log('tokenRefresh:' + token);
      console.log('tokenRefresh:' + token);
      firestore().collection("userToken").add({
        token:token
    })

    });
    // auth().currentUser.onTokenRefresh(token => {
    //   console.log('tokenRefresh:' + token);
    //   console.log('tokenRefresh:' + token);
    //   console.log('tokenRefresh:' + token);
    //   firestore().collection("userToken").add({
    //     token:token
    // })
    // });

    PushNotification.getChannels(function (channel_ids) {
      console.log('chanells: ' + channel_ids);
    });

    const granted = await messaging()
      .requestPermission()
      .catch(err => console.log(err));
    if (granted) {
      console.log('User granted messaging permissions!');

      createNotificationListners();
    } else {
      console.log('User declined messaging permissions :(');
    }
    await messaging().registerDeviceForRemoteMessages();
    return granted;
  };

  useEffect(() => {
    requestPermission();

    PushNotification.configure({
      onNotification: notification => {
        console.log('notificationOpen' + JSON.stringify(notification.data));
        setNotificationData(notification.data);
      },
    });
    return () => {
      setState({}); // This worked for me
    };
  }, []);

  const [noticationData, setNotificationData] = useState({});

  useEffect(() => {
    console.log('notificationReceived: ' + noticationData);
    // console.log('notificationReceived: ' + JSON.parse(JSON.stringify(noticationData)).url);
    
    Linking.openURL(""+noticationData.url+"").catch(err => console.error("Couldn't load page", err));
  }, [noticationData]);

  const createNotificationListners = async () => {
    PushNotification.createChannel(
      {
        channelId: 'channel-id', // (required)
        channelName: 'My channel', // (required)
        channelDescription: 'A channel to categorise your notifications', // (optional) default: undefined.
        playSound: true, // (optional) default: true
        soundName: 'notification.mp3', // (optional) See `soundName` parameter of `localNotification` function
        importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance
        vibrate: true, // (optional) default: true. Creates the default vibration pattern if true.
      },
      created => console.log(`createChannel returned '${created}'`), // (optional) callback returns whether the channel was created, false means it already existed.
    );

    // var loginStatus = await dateTimeHelper.getLoginStatus();

    // NOTIFICATION OPENED : When the application is opened from a quit state.

    messaging().onMessage(async remoteMessage => {
      // console.log("I'm receiveing new");
      var localNotification = {
        channelId: 'channel-id', // (required)
        channelName: 'My channel', // (required)
        // id: remoteMessage.data.notification_id, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
        title: remoteMessage.data.title, // (optional)
        message: remoteMessage.data.body, // (required)
        userInfo: remoteMessage.data, // (optional) default: {} (using null throws a JSON value '<null>' error)
        // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
        data: remoteMessage.data,
        soundName: 'default',
        onNotification: function (notification) {
          // console.log(' FETCHING NOTIFICATION ', notification)
          console.log('onNotification:');
          console.log('onNotification:' + notification);
        },
      };

      Platform.OS == 'android' &&
        (localNotification = {
          ...localNotification,

          channelId: 'channel-id', // (required)
          channelName: 'My channel', // (required)
          largeIcon: '', // (optional) default: "ic_launcher". Use "" for no large icon.
          smallIcon:
            Platform.Version >= 23 ? 'ic_launcher' : 'ic_launcher_round', // (optional) default: "ic_notification" with fallback for "ic_launcher". Use "" for default small icon.
          // bigPictureUrl: remoteMessage.notification.android.imageUrl, // (optional) default: undefined
          priority: 'high', // (optional) set notification priority, default: high
          ignoreInForeground: false, // (optional) if true, the notification will not be visible when the app is in the foreground (useful for parity with how iOS notifications appear). should be used in combine with `com.dieam.reactnativepushnotification.notification_foreground` setting
          onlyAlertOnce: false, // (optional) alert will open only once with sound and notify, default: false
          invokeApp: true, // (optional) This enable click on actions to bring back the application to foreground or stay in background, default: true
        });
      // console.log("I'm receiveing new1" + JSON.stringify(remoteMessage.data));
      // NotificationRedirector.getInstance().setData(remoteMessage.data)
      setNotificationData({});
      setNotificationData(remoteMessage.data);
      // console.log('notification data stringify basic', remoteMessage.data)
      PushNotification.localNotification(localNotification);
      // console.log('Message handled in the foreground!', remoteMessage.data)
      // // globalUtm = remoteMessage.data
      // console.log(
      //   'Message handled in the foreground123!',
      //   localNotification.data
      // )
      // store.dispatch(
      //   setNotificationMarked({
      //     ids: remoteMessage.data.msgId,
      //     action: 'received',
      //   })
      // )
    });

    messaging().setBackgroundMessageHandler(async remoteMessage => {
      // this.sendActionIos(remoteMessage)
      // globalUtm = remoteMessage.data
      // NotificationRedirector.getInstance().setData(remoteMessage.data)
      console.log("Background message handler")
      setNotificationData(
        remoteMessage.data
      );
      if(auth().currentUser !== null){
        const userId = auth().currentUser.uid
        firestore().collection("users").doc(userId).update({
          coins:firestore.FieldValue.increment(1)
        }).then(res => {
            console.log("Success update coins")
        }).catch(err => {
            console.log("Error update coins")
        })
      }
      // console.log(
      //   'notification data stringify backgroud',
      //   JSON.stringify(remoteMessage.data)
      // )
      // console.log('notification data stringify backgroud', remoteMessage.data)
      // console.log('Message handled in the background!', remoteMessage)
    });

    messaging().onNotificationOpenedApp(remoteMessage => {
      // NotificationRedirector.getInstance().setData(remoteMessage.data);
      console.log("on notification Opened App")
      setNotificationData(
        remoteMessage.data
      );
      
      // console.log(
      //   'notification on opened app',
      //   JSON.stringify(remoteMessage.data)
      // )
      // console.log('notification on opened app', remoteMessage.data)
    });

    messaging()
      .getInitialNotification()
      .then(remoteMessage => {
        if (remoteMessage) {
          console.log("Initial Notification")
          // NotificationRedirector.getInstance().setData(remoteMessage.data);
          setNotificationData(
            remoteMessage.data
          );
          // console.log(
          //   'notification get initial notification',
          //   remoteMessage.data
          // )
          // console.log(
          //   'notification get initial notification',
          //   JSON.stringify(remoteMessage.data)
          // )
        }
      });
  };

  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          options={{headerShown: false}}
          name="Login"
          component={LoginScreen}
        />
        <Stack.Screen
          options={{headerShown: false}}
          name="Home"
          component={HomeScreen}
        />
        <Stack.Screen
          options={{headerShown: false}}
          name="SendNotification"
          component={SendNotificationScreen}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

I have tried: cleaning npm, react-native cache, changing node versions, deleting pods reinstalling them, cleaning build in xcode. setting up firebase with rnfirebase.io ios setup guide

Hydria answered 19/2, 2023 at 18:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.