Can't register users in Firebase ERROR Invariant Violation: `new NativeEventEmitter()` requires a non-null argument., js engine: hermes

huangapple go评论69阅读模式
英文:

Can't register users in Firebase ERROR Invariant Violation: `new NativeEventEmitter()` requires a non-null argument., js engine: hermes

问题

I am trying to build an app created with React Native and I have I use `@react-native-firebase/app": "^17.5.0",
"@react-native-firebase/auth": "^17.5.0",
"@ react-native-firebase/firestore": "^17.5.0",

我正在尝试构建一个使用React Native创建的应用程序,并且我使用以下依赖项版本:

I run the App with npx react-native run-ios

我使用 npx react-native run-ios 命令来运行应用程序。

My ignorance prevents me from going ahead with the project, stalled after several days since I am trying to register users in Firebase with the logic that I show below, an auth.js file where the authentication is and firebase.js which has the logic of firebase. It is impossible for me.

我的无知阻碍了我继续进行项目,几天后停滞不前,因为我正在尝试使用下面展示的逻辑在Firebase中注册用户,其中包括处理身份验证的auth.js文件和包含Firebase逻辑的firebase.js。我无法成功。

I have changed the configuration of these files several times, and I cannot add here all the times I have made changes, but there have been several.

我已经多次更改了这些文件的配置,但无法在这里列出所有更改的次数,但已经进行了多次更改。

However I can't get it to register a new user.

然而,我无法使其注册新用户。

I EDIT THE QUESTION
I EDIT THE QUESTION

I have added the Podfile at the suggestion of a colleague.
I must also say that I have followed the instructions for React Native Firebase, but if I make all the changes suggested in AppDelegate.m and in Podfile, the project breaks and won't start again from the terminal nor from Xcode either.

我在同事的建议下添加了Podfile。
我还必须说,我已经按照React Native Firebase的说明进行了操作,但是如果我按照AppDelegate.m和Podfile中建议的所有更改进行操作,项目会中断,并且无法从终端或Xcode重新启动。

The error refers to the following file:

错误涉及以下文件:

/node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js

The app is still working, the errors have changed, but the one I'm logging now is the following:

应用程序仍在工作,错误已更改,但我现在正在记录的错误如下:

LOG Running "Cositas enter code here" with {"rootTag":1,"initialProps":{}}
ERROR Invariant Violation: new NativeEventEmitter() requires a non-null argument., js engine: hermes
at ?anon_0_ (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:132800:100)
at next (native)
at asyncGeneratorStep (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20867:26)
at _next (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20886:29)
at anonymous (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20891:14)
at tryCallTwo (/Users/distiller/react-native/sdks/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:61:9)
at doResolve (/Users/distiller/react-native/sdks/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:216:25)
at Promise (/Users/distiller/react-native/sdks/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:82:14)
at anonymous (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20883:25)
at apply (native)

LOG 运行带有 {"rootTag":1,"initialProps":{}} 的 "Cositas enter code here"
ERROR 不变违规:new NativeEventEmitter() 需要一个非空参数,js引擎:hermes
at ?anon_0_ (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:132800:100)
at next (native)
at asyncGeneratorStep (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20867:26)
at _next (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20886:29)
at anonymous (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20891:14)
at tryCallTwo (/Users/distiller/react-native/sdks/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:61:9)
at doResolve (/Users/distiller/react-native/sdks/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:216:25)
at Promise (/Users/distiller/react-native/sdks/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:82:14)
at anonymous (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20883:25)
at apply (native)

I

英文:

I am trying to build an app created with React Native and I have I use @react-native-firebase/app": "^17.5.0",
"@react-native-firebase/auth": "^17.5.0",
"@ react-native-firebase/firestore": "^17.5.0",

I run the App with npx react-native run-ios

My ignorance prevents me from going ahead with the project, stalled after several days since I am trying to register users in Firebase with the logic that I show below, an auth.js file where the authentication is and firebase.js which has the logic of firebase. It is impossible for me.

I have changed the configuration of these files several times, and I cannot add here all the times I have made changes, but there have been several.

However I can't get it to register a new user.

I EDIT THE QUESTION
I EDIT THE QUESTION

I have added the Podfile at the suggestion of a colleague.
I must also say that I have followed the instructions for React Native Firebase, but if I make all the changes suggested in AppDelegate.m and in Podfile, the project breaks and won't start again from the terminal nor from Xcode either.

The error refers to the following file:

/node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js

The app is still working, the errors have changed, but the one I'm logging now is the following:

 LOG  Running "Cositas enter code here" with {"rootTag":1,"initialProps":{}}
 ERROR  Invariant Violation: `new NativeEventEmitter()` requires a non-null argument., js engine: hermes
 at ?anon_0_ (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:132800:100)
    at next (native)
    at asyncGeneratorStep (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20867:26)
    at _next (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20886:29)
    at anonymous (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20891:14)
    at tryCallTwo (/Users/distiller/react-native/sdks/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:61:9)
    at doResolve (/Users/distiller/react-native/sdks/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:216:25)
    at Promise (/Users/distiller/react-native/sdks/hermes/build_iphonesimulator/lib/InternalBytecode/InternalBytecode.js:82:14)
    at anonymous (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false&modulesOnly=false&runModule=true&app=org.reactjs.native.example.ApuntesDelCampo:20883:25)
    at apply (native)

I understand that the causes can be several, that's why I'm here, since I can't find the way to do it after many tries and many changes that I made suggested by other similar problems found on Stackoverflow. Maybe someone will see the error that I have in the code or can suggest a correct configuration.

I don't understand if the iOS configuration may be affecting it, whenever I run the "pod install" all the dependencies are installed again and it shows the :

[!] The following Swift pods cannot yet be integrated as static libraries:

    The Swift pod `FirebaseCoreInternal` depends upon `GoogleUtilities`, which does not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.

I show the files and I hope you can give me some idea to be able to correct this and move on,

============ Podfile =======

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, min_ios_version_supported
prepare_react_native_project!

# If you are using a `react-native-flipper` your iOS build will fail when `NO_FLIPPER=1` is set.
# because `react-native-flipper` depends on (FlipperKit,...) that will be excluded
#
# To fix this you can also exclude `react-native-flipper` using a `react-native.config.js`
# ```js
# module.exports = {
#   dependencies: {
#     ...(process.env.NO_FLIPPER ? { 'react-native-flipper': { platforms: { ios: null } } } : {}),
# ```
flipper_config = ENV['NO_FLIPPER'] == "1" ? FlipperConfiguration.disabled : FlipperConfiguration.enabled

linkage = ENV['USE_FRAMEWORKS']
if linkage != nil
  Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
  use_frameworks! :linkage => linkage.to_sym
end

target 'ApuntesDelCampo' do
  config = use_native_modules!

  # Flags change depending on the env values.
  flags = get_default_flags()

  use_react_native!(
    :path => config[:reactNativePath],
    # Hermes is now enabled by default. Disable by setting this flag to false.
    # Upcoming versions of React Native may rely on get_default_flags(), but
    # we make it explicit here to aid in the React Native upgrade process.
    :hermes_enabled => flags[:hermes_enabled],
    :fabric_enabled => flags[:fabric_enabled],
    # Enables Flipper.
    #
    # Note that if you have use_frameworks! enabled, Flipper will not work and
    # you should disable the next line.
    :flipper_configuration => flipper_config,
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  target 'ApuntesDelCampoTests' do
    inherit! :complete
    # Pods for testing
  end

  post_install do |installer|
    react_native_post_install(
      installer,
      # Set `mac_catalyst_enabled` to `true` in order to apply patches
      # necessary for Mac Catalyst builds
      :mac_catalyst_enabled => false
    )
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end

========. RegisterScreen.js ==================

import React, { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, Alert } from 'react-native';
import { registerUser } from '../../services/auth'

import styles from './AuthStyles/RegisterScreenStyles'

const RegisterScreen = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [username, setUsername] = useState('');

  const handleRegister = async () => {
    if (email && password && username) {
      const { success, error } = await registerUser(email, password, username);

      if (success) {
        // Registro exitoso
        Alert.alert('Registro exitoso', '¡Usuario registrado correctamente!');
      } else {
        // Error en el registro
        Alert.alert('Error de registro', error);
      }
    } else {
      // Validación de campos vacíos
      Alert.alert('Campos vacíos', 'Por favor, completa todos los campos.');
    }
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Registro</Text>
      <TextInput
        style={styles.input}
        placeholder="Nombre de usuario"
        value={username}
        onChangeText={ setUsername}
      />
      <TextInput
        style={styles.input}
        placeholder="Correo electrónico"
        value={email}
        onChangeText={setEmail}
      />
      <TextInput
        style={styles.input}
        placeholder="Contraseña"
        secureTextEntry
        value={password}
        onChangeText={setPassword}
      />
      <TouchableOpacity style={styles.button} onPress={handleRegister}>
        <Text style={styles.buttonText}>Registrarse</Text>
      </TouchableOpacity>
    </View>
  )
}

export default RegisterScreen;

===========. auth.js. =============

import { firebaseFirestore, firebaseAuth } from "./firebase";


// Registro de usuario
export const registerUser = async (email, password, username) => {
  try {
    const { user } = await firebaseAuth.createUserWithEmailAndPassword(email, password);

    // Almacenar el nombre de usuario en Firestore
    await firebaseFirestore.collection('users').doc(user.uid).set({
      username,
    });

    return { success: true, user };
  } catch (error) {
    return { success: false, error: error.message };
  }
};

========. firebase.js. ========

import firebase from '@react-native-firebase/app'
import '@react-native-firebase/firestore'
import '@react-native-firebase/auth'

// Configura Firebase
const firebaseConfig = {
  apiKey: "xxxxx",
  authDomain: "xxxxx",
  projectId: "cxxxxx",
  storageBucket: "xxxx",
  messagingSenderId: "xxxx",
  appId: "xxxxxx"
};

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig)
}

const firebaseFirestore = firebase.firestore();
const firebaseAuth = firebase.auth();

export { firebaseFirestore, firebaseAuth }

答案1

得分: 3

当你运行 pod install 时,没有静态库会抛出错误,实际上不会安装 Firebase。

禁用 flipper,因为 flipper 与静态库不兼容:

# 注意,如果启用了 use_frameworks!,则启用 Flipper 将不起作用
# :flipper_configuration => flipper_config,<-- 注释此行
# 指向你应用根目录的绝对路径

target 'ApuntesDelCampo' do 内,在 flags = ... 之前添加以下两行:

use_frameworks! :linkage => :static

$RNFirebaseAsStaticFramework = true

# 根据环境值更改标志。
flags = get_default_flags()

还要确保已将 GoogleService-Info.plist 添加到你的项目中。

现在再次运行 pod install,并尝试安装应用程序。

英文:

When you're running pod install without static library, it is throwing an error and not actually installing Firebase.

Disable flipper since flipper doesn't work with static lib:

# Note that if you have use_frameworks! enabled, Flipper will not work if enabled
# :flipper_configuration => flipper_config, <-- comment this line
# An absolute path to your application root

Inside the target 'ApuntesDelCampo' do add two following just above flags = ...:

use_frameworks! :linkage => :static

$RNFirebaseAsStaticFramework = true

# Flags change depending on the env values.
flags = get_default_flags()

And also make sure you have added GoogleService-Info.plist to your project.

Now run pod install again, and try installing the App.

huangapple
  • 本文由 发表于 2023年6月5日 16:16:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76404603.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定