react-native-firebase
react-native-firebase copied to clipboard
[🐛] [Android] 🔥 Firestore useEmulator throws an error (instance has already been initialized) when refreshing with hot reload and metro bundler
Issue
Hi and thanks for the awesome libs!
I updated recently, and encountered a bug on Android: when hot-reloading the codebase and using the Firestore emulator, I got an error message saying the emulator has already been initialized.
Error: [firestore/unknown] Cannot call useEmulator() after instance has already been initialized.
NativeFirebaseError: [firestore/unknown] Cannot call useEmulator() after instance has already been initialized.
http://10.0.0.20:8081/index.bundle?platform=android&dev=true&minify=false&app=app.courtisan.dev&modulesOnly=false&runModule=true:1404:42
loadModuleImplementation@http://10.0.0.20:8081/index.bundle?platform=android&dev=true&minify=false&app=app.courtisan.dev&modulesOnly=false&runModule=true:290:14
guardedLoadModule@http://10.0.0.20:8081/index.bundle?platform=android&dev=true&minify=false&app=app.courtisan.dev&modulesOnly=false&runModule=true:163:47
global code@http://10.0.0.20:8081/index.bundle?platform=android&dev=true&minify=false&app=app.courtisan.dev&modulesOnly=false&runModule=true:212728:4
Project Files
Javascript
Click To Expand
package.json:
{
"name": "project",
"version": "1.1.0",
"private": true,
"scripts": {},
"dependencies": {
"@invertase/react-native-apple-authentication": "^2.1.1",
"@react-native-async-storage/async-storage": "^1.14.1",
"@react-native-community/blur": "^3.6.0",
"@react-native-community/cameraroll": "^4.0.2",
"@react-native-community/datetimepicker": "^3.2.0",
"@react-native-community/google-signin": "^5.0.0",
"@react-native-community/masked-view": "^0.1.10",
"@react-native-firebase/analytics": "^12.0.0",
"@react-native-firebase/app": "^12.0.0",
"@react-native-firebase/auth": "^12.0.0",
"@react-native-firebase/crashlytics": "^12.0.0",
"@react-native-firebase/firestore": "^12.0.0",
"@react-native-firebase/functions": "^12.0.0",
"@react-native-firebase/messaging": "^12.0.0",
"@react-native-firebase/perf": "^12.0.0",
"@react-native-firebase/remote-config": "^12.0.0",
"@react-native-picker/picker": "^1.9.12",
"@react-navigation/bottom-tabs": "^5.11.8",
"@react-navigation/native": "^5.9.3",
"@react-navigation/stack": "^5.14.3",
"i18next": "^19.8.4",
"lottie-ios": "3.2.3",
"lottie-react-native": "^4.0.3",
"luxon": "^1.27.0",
"pluralize": "^8.0.0",
"react": "17.0.1",
"react-i18next": "^11.8.10",
"react-native": "0.64.1",
"react-native-config": "^1.4.2",
"react-native-fast-image": "^8.3.4",
"react-native-fbsdk-next": "^4.3.0",
"react-native-gesture-handler": "^1.10.3",
"react-native-image-picker": "^3.3.2",
"react-native-linear-gradient": "^2.5.6",
"react-native-localize": "^2.0.2",
"react-native-modal-datetime-picker": "^9.2.0",
"react-native-reanimated": "^1.13.2",
"react-native-safe-area-context": "^3.2.0",
"react-native-screens": "^2.18.1",
"react-native-shared-element": "^0.8.2",
"react-native-svg": "^12.1.1",
"react-native-webview": "^11.6.2",
"react-redux": "^7.2.2",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
"rn-range-slider": "^2.0.4"
},
"devDependencies": {
"@babel/core": "^7.12.10",
"@babel/runtime": "^7.12.5",
"@react-native-community/eslint-config": "^2.0.0",
"@types/jest": "^26.0.24",
"@types/luxon": "^1.27.1",
"@types/react": "^17.0.15",
"@types/react-native": "^0.64.12",
"@types/react-test-renderer": "^17.0.1",
"babel-jest": "^26.6.3",
"babel-plugin-module-resolver": "^4.1.0",
"chalk": "^4.1.1",
"dotenv": "^10.0.0",
"eslint": "^7.26.0",
"eslint-plugin-prettier": "^3.4.0",
"jest": "^26.6.3",
"metro-react-native-babel-preset": "^0.64.0",
"prettier": "2.3.0",
"puppeteer": "^10.1.0",
"react-native-clean-project": "^3.6.4",
"react-test-renderer": "17.0.1",
"redux-devtools-extension": "^2.13.8",
"typescript": "^4.3.5"
},
"jest": {
"preset": "react-native"
}
}
firebase.json for react-native-firebase v6:
{
"react-native": {
"analytics_auto_collection_enabled": false,
"messaging_auto_init_enabled": true,
"crashlytics_debug_enabled": false,
"crashlytics_disable_auto_disabler": true,
"crashlytics_auto_collection_enabled": true,
"crashlytics_is_error_generation_on_js_crash_enabled": true,
"crashlytics_javascript_exception_handler_chaining_enabled": false
}
}
iOS
Click To Expand
ios/Podfile:
- [ ] I'm not using Pods
- [x] I'm using Pods and my Podfile looks like:
# N/A
AppDelegate.m:
// N/A
Android
Click To Expand
Have you converted to AndroidX?
- [x] my application is an AndroidX application?
- [x] I am using
android/gradle.settingsjetifier=truefor Android compatibility? - [ ] I am using the NPM package
jetifierfor react-native compatibility?
android/build.gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "29.0.3"
minSdkVersion = 21
compileSdkVersion = 29
targetSdkVersion = 29
ndkVersion = "20.1.5948944"
}
repositories {
google()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:4.1.0")
classpath("com.google.gms:google-services:4.3.3")
classpath('com.google.firebase:perf-plugin:1.4.0')
classpath("com.google.firebase:firebase-crashlytics-gradle:2.6.1")
}
}
allprojects {
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
google()
jcenter()
maven { url 'https://www.jitpack.io' }
}
}
android/app/build.gradle:
project.ext.envConfigFiles = [
release: ".env.production",
debug: ".env.development",
stagingrelease: ".env.staging",
]
apply plugin: "com.android.application"
apply plugin: "com.google.gms.google-services"
apply plugin: "com.google.firebase.crashlytics"
apply plugin: 'com.google.firebase.firebase-perf'
apply from: project(":react-native-config").projectDir.getPath() + "/dotenv.gradle"
import com.android.build.OutputFile
/**
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
* and bundleReleaseJsAndAssets).
* These basically call `react-native bundle` with the correct arguments during the Android build
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
* bundle directly from the development server. Below you can see all the possible configurations
* and their defaults. If you decide to add a configuration block, make sure to add it before the
* `apply from: "../../node_modules/react-native/react.gradle"` line.
*
* project.ext.react = [
* // the name of the generated asset file containing your JS bundle
* bundleAssetName: "index.android.bundle",
*
* // the entry file for bundle generation. If none specified and
* // "index.android.js" exists, it will be used. Otherwise "index.js" is
* // default. Can be overridden with ENTRY_FILE environment variable.
* entryFile: "index.android.js",
*
* // https://reactnative.dev/docs/performance#enable-the-ram-format
* bundleCommand: "ram-bundle",
*
* // whether to bundle JS and assets in debug mode
* bundleInDebug: false,
*
* // whether to bundle JS and assets in release mode
* bundleInRelease: true,
*
* // whether to bundle JS and assets in another build variant (if configured).
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
* // The configuration property can be in the following formats
* // 'bundleIn${productFlavor}${buildType}'
* // 'bundleIn${buildType}'
* // bundleInFreeDebug: true,
* // bundleInPaidRelease: true,
* // bundleInBeta: true,
*
* // whether to disable dev mode in custom build variants (by default only disabled in release)
* // for example: to disable dev mode in the staging build type (if configured)
* devDisabledInStaging: true,
* // The configuration property can be in the following formats
* // 'devDisabledIn${productFlavor}${buildType}'
* // 'devDisabledIn${buildType}'
*
* // the root of your project, i.e. where "package.json" lives
* root: "../../",
*
* // where to put the JS bundle asset in debug mode
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
*
* // where to put the JS bundle asset in release mode
* jsBundleDirRelease: "$buildDir/intermediates/assets/release",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in debug mode
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in release mode
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
*
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
* // date; if you have any other folders that you want to ignore for performance reasons (gradle
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
* // for example, you might want to remove it from here.
* inputExcludes: ["android/**", "ios/**"],
*
* // override which node gets called and with what additional arguments
* nodeExecutableAndArgs: ["node"],
*
* // supply additional arguments to the packager
* extraPackagerArgs: []
* ]
*/
project.ext.react = [
enableHermes: false, // clean and rebuild if changing
]
apply from: "../../node_modules/react-native/react.gradle"
/**
* Set this to true to create two separate APKs instead of one:
* - An APK that only works on ARM devices
* - An APK that only works on x86 devices
* The advantage is the size of the APK is reduced by about 4MB.
* Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore.
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc-intl:+'
/**
* Whether to enable the Hermes VM.
*
* This should be set on project.ext.react and mirrored here. If it is not set
* on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
* and the benefits of using Hermes will therefore be sharply reduced.
*/
def enableHermes = project.ext.react.get("enableHermes", false);
android {
ndkVersion rootProject.ext.ndkVersion
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "app.example"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 47
versionName "1.2.0"
resValue "string", "build_config_package", "app.example"
multiDexEnabled true
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
release {
keyAlias System.getenv('KEY_ALIAS')
keyPassword System.getenv('KEY_PASSWORD')
storeFile file('courtisan-release.keystore')
storePassword System.getenv('KEYSTORE_PASSWORD')
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
applicationIdSuffix ".dev"
}
release {
signingConfig signingConfigs.release
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
// firebaseCrashlytics {
// nativeSymbolUploadEnabled true
// }
}
stagingrelease {
initWith release
applicationIdSuffix ".staging"
matchingFallbacks = ['release', 'debug']
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
defaultConfig.versionCode * 1000 + versionCodes.get(abi)
}
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
exclude group:'com.squareup.okhttp3', module:'okhttp'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
implementation 'androidx.multidex:multidex:2.0.1'
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
android/settings.gradle:
rootProject.name = 'Example'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
MainApplication.java:
package app.courtisan;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* @param context
* @param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.example.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.example">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_notification" />
</application>
</manifest>
Environment
Click To Expand
react-native info output:
info Fetching system and libraries information...
System:
OS: macOS 11.5.2
CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
Memory: 425.59 MB / 32.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 14.17.2 - /var/folders/dp/q1cz4t1j1rb0rtgqsftrq3d80000gn/T/yarn--1631782184641-0.3327990080587764/node
Yarn: 1.22.11 - /var/folders/dp/q1cz4t1j1rb0rtgqsftrq3d80000gn/T/yarn--1631782184641-0.3327990080587764/yarn
npm: 6.14.13 - ~/.nvm/versions/node/v14.17.2/bin/npm
Watchman: 2021.08.30.00 - /usr/local/bin/watchman
Managers:
CocoaPods: 1.11.1 - /Users/doctor/.rbenv/shims/pod
SDKs:
iOS SDK:
Platforms: iOS 14.5, DriverKit 20.4, macOS 11.3, tvOS 14.5, watchOS 7.4
Android SDK: Not Found
IDEs:
Android Studio: 4.1 AI-201.8743.12.41.7199119
Xcode: 12.5.1/12E507 - /usr/bin/xcodebuild
Languages:
Java: 14.0.2 - /usr/bin/javac
npmPackages:
@react-native-community/cli: Not Found
react: 17.0.1 => 17.0.1
react-native: 0.64.1 => 0.64.1
react-native-macos: Not Found
npmGlobalPackages:
*react-native*: Not Found
- Platform that you're experiencing the issue on:
- [ ] iOS
- [x] Android
- [ ] iOS but have not tested behavior on Android
- [ ] Android but have not tested behavior on iOS
- [ ] Both
react-native-firebaseversion you're using that has this issue:12.7.5
Firebasemodule(s) you're using that has the issue:Firestore
- Are you using
TypeScript?Y & 4.3.5
- 👉 Check out
React Native FirebaseandInvertaseon Twitter for updates on the library.
Can you please make sure you are on current versions and confirm it still happens? package.json says 12.0.0 but 12.8.0 is current Looks similar to #5650 but obviously firestore vs rtdb Can you edit the title to contain some useful content vs the default?
Most important for prioritization, can you say if it still works afterwards? Stated differently: Yes this is an error and probably irritating but does it still actually work even after the error? If it is like #5650 it should not block you, I hope
Hi,
I checked, package.json is still on ^12.0.0, but my yarn.lock is effectively at 12.7.5.
I didn't see #5650 but it seems similar (if not identical).
Sorry for the title, I fixed it.
Now that you said it, it doesn't block: it only shows the Promise rejection call and then just act normally, so it still works afterwards. From what I understand, the Firestore instance is not resetted after a hot reload, but instead just reused (which seems not to be the case neither on iOS or with others emulators like Auth). So we get the warning. I don't get the warning if I'm cold launching the app for the first time, probably because the Firestore instance is not yet initialized.
I'm more an iOS-person, so it's a little bit hard to dive into Java Android source code, but tell me if I can be of any help.
Hey @ghivert thanks very much for checking whether it still works afterwards, this is definitely still an issue to work through, but it does help prioritize. Unfortunately (for those affected) it means I will likely not be able to get to this one (or #5650) quickly since they do seem to work after despite the acknowledged awful experience of it throwing up the promise rejection.
I guess what we will need to do, in case anyone has time for a PR before I can examine it, is to either
- avoid reconfigure: store state somehow so we do not attempt to reconfigure (that is: a member variable in java that stores whether useEmulator has been called, and then avoids calling on native side if already called)
- throw away native on reload: I believe onCatalystInstanceDestroy is a method the native module can override, and it could perhaps throw away the native java instance of firestore? Unsure if it wouuld work - I don't know how they are storing state internally and it might be static / non-expunge-able - example of onCatalystInstanceDestroy in firestore/android/src/reactnative/java/io/invertase/firebase/firestore/ReactNativeFirebaseFirestoreCollectionModule.java)
- catch and ignore the specific exception in the native code, with a "warning" logged (
Log.win android terms) and an API doc note (in index.d.ts for the useEmulator calls) that notes changes to useEmulator parameters will not take affect until app restart, reloads won't do it)
Hello 👋, to help manage issues we automatically close stale issues. This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?
This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.