简体   繁体   中英

ReactNative initialize Firebase at app start?

I have a app.js file, in which I'm creating my NavigationContainer and adding in some screens and calling a function called init (from my firebase.js file, see below) to initialize my app for Firebase.

I also got a LoginScreen.js file, in which I'm handling login / register processes with firebase. If the user is logged in, the app loads the HomeScreen.js file immediatly. The firebase config is in a seperate file (firebase.js), which looks like this:

// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app'
import { getDatabase } from 'firebase/database'


// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
  // Imagine a config file here //
};

const init = () => {
  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const db = getDatabase(app);
}

export { init };
// somehow need to export db here

I'm now adding a todo list in a new screen the user can navigate to from my HomeScreen. Here I need the db from my firebase.js, because I want to save the objects there. However, the db seems to be "undefined", probably because I can't access it because I haven't exported it from the firebase.js file.

I tried removing the init function from my app.js, but that throws an "No Firebase App has been created" issue.

Question: How can I initialize my app in the firebase.js, make sure it get's called first AND have a working db exported in the same firebase.js file?

I found a way (just in case this helps anyone in the future): Simply remove the init function and have the app and db exported, like so:

// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app'
import { getDatabase } from 'firebase/database'


// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
  //imagine config here
};

const app = initializeApp(firebaseConfig);
const db = getDatabase(app);

export { app, db };

Then, import app from firebase.js in your app.js file and call it, like so:

import { app } from './firebase';

{ /* this calls the firebase.js and initializes the app */ }
app

export default function App() { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM