In React, if we fetch data from one Firebase project, we'll have a file Firebase.js
:
jsximport firebase from 'firebase' var firstConfig = { apiKey: "API_KEY", authDomain: "AUTH_DOMAIN", databaseURL: "DATABASE_URL", projectId: "PROJECT_ID", storageBucket: "STORAGE_BUCKET", messagingSenderId: "MESSAGING_SENDER_ID" }; firebase.initializeApp(firstConfig); export default firebase;
To add a second project, we need to use firebase.initializeApp(secondConfig, "other")
function.
Example:
jsximport firebase from 'firebase' var firstConfig = { apiKey: "API_KEY", authDomain: "AUTH_DOMAIN", databaseURL: "DATABASE_URL", projectId: "PROJECT_ID", storageBucket: "STORAGE_BUCKET", messagingSenderId: "MESSAGING_SENDER_ID" }; var secondConfig = { apiKey: "API_KEY", authDomain: "AUTH_DOMAIN", databaseURL: "DATABASE_URL", projectId: "PROJECT_ID", storageBucket: "STORAGE_BUCKET", messagingSenderId: "MESSAGING_SENDER_ID" }; firebase.initializeApp(firstConfig); export const other = firebase.initializeApp(secondConfig, "other"); export default firebase;
Now, we can fetch data from both projects as follows:
jsximport React, { useEffect } from 'react'; import firebase, { other } from './Firebase'; const App = () => { useEffect( () => { // Fetching data from default project firebase.database().ref().on('value', snapshot => { //... }); // Fetching data from default project other.database().ref().on('value', snapshot => { //... }); }, []); return( // ... ); } export default App;
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.