react-native-firebase icon indicating copy to clipboard operation
react-native-firebase copied to clipboard

🔥 [🐛] Error when using Realtime Database useEmulator after refreshing metro bundler

Open raulcontrerasrubio opened this issue 4 years ago • 6 comments

Issue

I'm using the Realtime Database emulator. On the first load everything is ok, however, if I press "r" on the metro bundler to refresh the app a red screen error shows up with the next dismissable message:

"Exception: 'Cannot connect to emulator after database initialization. 
Call useEmulator(host:port:) before creating a database reference or trying to load data.' was thrown while invoking useEmulator on target RNFBDatabaseModule 
with params ("[DEFAULT]", "<null>", localhost, 9000)

Here two screenshots of the rest of the error: Stack trace 1 Stack trace 2

./src/services/firebase/client.ts

import firebaseApp from '@react-native-firebase/app';
import '@react-native-firebase/auth';
import '@react-native-firebase/database';
import '@react-native-firebase/storage';

export const app = firebaseApp.app();
export const auth = firebaseApp.auth();
export const db = firebaseApp.database();
export const storage = firebaseApp.storage();

if(__DEV__){
  auth.useEmulator("http://localhost:9099")
  db.useEmulator("localhost", 9000)
  storage.useEmulator("localhost", 9199)
}


export default firebaseApp;

./src/services/firebase/index.ts

import {app, auth, db, storage} from './client';

export {
  app, auth, db, storage,
}

./src/App.tsx

import React, {useEffect} from 'react';
import {
  SafeAreaView,
  Text,
} from 'react-native';
import {auth} from './services/firebase';

const App = () => {
  useEffect(() => {
    const unsubscribeFromUserChanges = auth.onAuthStateChanged(user => {
      if(user){
        console.log("Logged user")
      }else{
        console.log("Guest user");
      }
    });

    return () => {
      unsubscribeFromUserChanges();
    }
  }, [])

  return (
    <SafeAreaView>
      <Text>App</Text>
    </SafeAreaView>
  );
};

export default App;


Project Files

Javascript

Click To Expand

package.json:

{
  "name": "react-native-firebase-auth",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev:android": "react-native run-android",
    "dev:ios": "react-native run-ios",
    "start": "react-native start",
    "start:cache": "react-native start --reset-cache",
    "start:emulator": "firebase emulators:start",
    "ios:pods": "cd ios; pod install --repo-update; cd ..",
    "test": "jest",
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx"
  },
  "dependencies": {
    "@react-native-firebase/app": "^12.7.3",
    "@react-native-firebase/auth": "^12.7.3",
    "@react-native-firebase/database": "^12.7.3",
    "@react-native-firebase/storage": "^12.7.3",
    "react": "17.0.2",
    "react-native": "0.65.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "@types/jest": "^26.0.23",
    "@types/react-native": "^0.64.5",
    "@types/react-test-renderer": "^16.9.2",
    "babel-jest": "^26.6.3",
    "eslint": "^7.14.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.66.0",
    "react-native-codegen": "^0.0.7",
    "react-test-renderer": "17.0.2",
    "typescript": "^3.8.3"
  },
  "resolutions": {
    "@types/react": "^17"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
}

firebase.json for react-native-firebase v6:

{
  "react-native": {
    "android_task_executor_maximum_pool_size": 10,
    "android_task_executor_keep_alive_seconds": 3
  },
  "database": {
    "rules": "database.rules.json"
  },
  "functions": {
    "predeploy": "npm --prefix \"$RESOURCE_DIR\" run build"
  },
  "storage": {
    "rules": "storage.rules"
  },
  "emulators": {
    "auth": {
      "port": 9099
    },
    "functions": {
      "port": 5001
    },
    "database": {
      "port": 9000
    },
    "pubsub": {
      "port": 8085
    },
    "storage": {
      "port": 9199
    },
    "ui": {
      "enabled": true,
      "port": 8192
    }
  }
}

iOS

Click To Expand

ios/Podfile:

  • [ ] I'm not using Pods
  • [x] I'm using Pods and my Podfile looks like:
require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '11.0'

target 'ReactNativeFirebaseAuth' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )

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

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
  end
end

AppDelegate.m:

#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <Firebase.h>

#ifdef FB_SONARKIT_ENABLED
#import <FlipperKit/FlipperClient.h>
#import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
#import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
#import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
#import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
#import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>

static void InitializeFlipper(UIApplication *application) {
  FlipperClient *client = [FlipperClient sharedClient];
  SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
  [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
  [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
  [client addPlugin:[FlipperKitReactPlugin new]];
  [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
  [client start];
}
#endif

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  
#ifdef FB_SONARKIT_ENABLED
  InitializeFlipper(application);
#endif
  
  if ([FIRApp defaultApp] == nil) {
      [FIRApp configure];
    }

  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"ReactNativeFirebaseAuth"
                                            initialProperties:nil];

  if (@available(iOS 13.0, *)) {
      rootView.backgroundColor = [UIColor systemBackgroundColor];
  } else {
      rootView.backgroundColor = [UIColor whiteColor];
  }

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end


Android

Click To Expand

Have you converted to AndroidX?

  • [ ] my application is an AndroidX application?
  • [ ] I am using android/gradle.settings jetifier=true for Android compatibility?
  • [ ] I am using the NPM package jetifier for react-native compatibility?

android/build.gradle:

// N/A

android/app/build.gradle:

// N/A

android/settings.gradle:

// N/A

MainApplication.java:

// N/A

AndroidManifest.xml:

<!-- N/A -->

Environment

Click To Expand

react-native info output:

System:
    OS: macOS 11.5.1
    CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 272.50 MB / 32.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 12.16.1 - ~/.nvm/versions/node/v12.16.1/bin/node
    Yarn: 1.22.10 - ~/.nvm/versions/node/v12.16.1/bin/yarn
    npm: 7.15.0 - ~/.nvm/versions/node/v12.16.1/bin/npm
    Watchman: 2021.06.07.00 - /usr/local/bin/watchman
  Managers:
    CocoaPods: 1.10.1 - /Users/raul/.rubies/ruby-2.7.1/bin/pod
  SDKs:
    iOS SDK:
      Platforms: iOS 14.5, DriverKit 20.4, macOS 11.3, tvOS 14.5, watchOS 7.4
    Android SDK:
      API Levels: 23, 28, 29, 30
      Build Tools: 28.0.3, 29.0.2, 29.0.3, 30.0.2, 30.0.3
      System Images: android-22 | Google APIs Intel x86 Atom, android-23 | Google APIs Intel x86 Atom, android-24 | Google APIs Intel x86 Atom, android-25 | Google APIs Intel x86 Atom, android-28 | Intel x86 Atom_64, android-29 | Google APIs Intel x86 Atom, android-30 | Google APIs Intel x86 Atom, android-30 | Google Play Intel x86 Atom
      Android NDK: Not Found
  IDEs:
    Android Studio: 4.1 AI-201.8743.12.41.6953283
    Xcode: 12.5.1/12E507 - /usr/bin/xcodebuild
  Languages:
    Java: 1.8.0_242 - /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: 17.0.2 => 17.0.2
    react-native: 0.65.1 => 0.65.1
    react-native-macos: Not Found
  npmGlobalPackages:
    *react-native*: Not Found
  • Platform that you're experiencing the issue on:
    • [x] iOS
    • [ ] Android
    • [ ] iOS but have not tested behavior on Android
    • [ ] Android but have not tested behavior on iOS
    • [ ] Both
  • react-native-firebase version you're using that has this issue:
    • 12.7.3
  • Firebase module(s) you're using that has the issue:
    • @react-native-firebase/database
  • Are you using TypeScript?
    • Yes, 3.8.3

raulcontrerasrubio avatar Aug 26 '21 18:08 raulcontrerasrubio

Oh, that sounds frustrating. I know hot-reload is really important in a dev cycle but I'm not sure what we can do about this - out of curiosity, does it still work and connect to the emulator after the hot reload? Stated differently, is this an error message that is ignorable because things are still working afterwards, or does this imply that the connection is fully dead afterwards?

mikehardy avatar Aug 26 '21 18:08 mikehardy

The connection to the emulator is still working after dismissing the error.

However it seems strange that the other emulators (auth, storage) work perfectly fine and the only emulator that shows this error is the realtime emulator. It's like if after refreshing react native the other emulators dropped their references to their configured instances and started fresh but the database emulator kept an old copy and raised an error in consequence. I don't really know how it works, but maybe it helps to solve this because it's very annoying.

Thanks for your quick response

raulcontrerasrubio avatar Aug 26 '21 19:08 raulcontrerasrubio

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.

stale[bot] avatar Apr 18 '22 18:04 stale[bot]

I also have this issue and after hot reload I can't use the app anymore so I have to restart the app. Tested on iOS simulator using expo devclient with RNFB config plugins

Exception 'Cannot connect to emulator after database initialization. Call useEmulator(host:port:) before creating a database reference or trying to load data.' was thrown while invoking useEmulator on target RNFBDatabaseModule with params (
    "[DEFAULT]",
    "https://{dburl}.firebasedatabase.app",
    "127.0.0.1",
    9000
)
callstack: (
	0   CoreFoundation                      0x000000011b0c9bb4 __exceptionPreprocess + 242
	1   libobjc.A.dylib                     0x000000011740bbe7 objc_exception_throw + 48
	2   CoreFoundation                      0x000000011b0c9a92 -[NSException initWithCoder:] + 0
	3   Appname                             0x00000001046857b5 -[FIRDatabase useEmulatorWithHost:port:] + 213
	4   Appname                             0x000000010516a61a -[RNFBDatabaseModule useEmulator::::] + 170
	5   CoreFoundation                      0x000000011b0d047c __invoking___ + 140
	6   CoreFoundation                      0x000000011b0cd872 -[NSInvocation invoke]<…>

Lib version

"@react-native-firebase/app": "^14.9.1",
"@react-native-firebase/auth": "^14.2.1",
"@react-native-firebase/database": "^14.9.4",
"@react-native-firebase/firestore": "^14.9.1",

kotano avatar May 21 '22 13:05 kotano

I run into a similar issue on "@react-native-firebase/database": "^14.11.0", without using expo

psdewar avatar Jul 07 '22 15:07 psdewar

@psdewar2 this behavior will not change until there is a PR that changes it at which point the issue will be closed via a link to a relevant merged PR

mikehardy avatar Jul 07 '22 16:07 mikehardy

any update on this? having the same issue

Alex1899 avatar Sep 30 '22 17:09 Alex1899

@Alex1899 "metoo" comments provide no value, you and all future people may refer to this comment as authoritative:

this behavior will not change until there is a PR that changes it at which point the issue will be closed via a link to a relevant merged PR

There are no secret updates, there is no secret work. If you are motivated to close this, I/we will happily collaborate on a PR you provide

mikehardy avatar Sep 30 '22 17:09 mikehardy