Rewrite firebase service using dynamic import - javascript

Please help me to rewrite the code to use the dynamic import feature.
Unfortunately i have no idea how to use dynamic import in module.
import firebase from 'firebase/app';
import 'firebase/firestore';
const config = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
};
const initApp = firebase.initializeApp(config).firestore();
initApp.settings({
timestampsInSnapshots: true,
});
const app = firebase.app().firestore();
export default !firebase.apps.length ? initApp : app;
What i tried
import('firebase/app')
.then((firebase) => {
firebase.initializeApp(config).firestore();
});

That's because the firebase variable you want is in fact inside a default property. You could do something like this:
import('firebase/app')
.then(firebase => {
firebase.default.initializeApp(config).firestore();
});
A complete suggestion with async functions bellow:
// firebase-service.js
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MSG_SENDER_ID,
appId: process.env.FIREBASE_APP_ID
};
let db;
async function getFirestore () {
if (!db) {
const { default: firebase } = await import('firebase/app');
await import('firebase/firestore');
const app = firebase.initializeApp(firebaseConfig);
db = app.firestore();
}
return db;
}
export { getFirestore };

Related

Firebase Cannot read properties of undefined initializeApp

In a video I watched, she writes the firebase codes like this, but it gives me an error, I guess, can you help me how to make a new one from an old section?
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
const firebaseConfig = {
apiKey: "XXX",
authDomain: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX"
};
firebase.initializeApp(firebaseConfig);
const projectAuth = firebase.auth();
const projectFirestore = firebase.firestore();
const timestamp = firebase.firestore.FieldValue.serverTimestamp;
export { projectAuth, projectFirestore, timestamp };
......................

How to initialize firebase in firebase version 9 (firebase v9)?

I used to initialize my firebase app using this method -
import firebase from "firebase/app";
import "firebase/auth";
const config = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
};
export default function initFirebase() {
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
}
I am upgrading my firebase version to 9 and I need a way to initialize my app using es modules.
I tried this -
import { initializeApp, getApps, getApp } from "firebase/app";
const config = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
};
export default function initFirebase() {
getApps().length === 0 ? initializeApp(config) : getApp();
}
But I am getting this error -
FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app-compat/no-app).
Why don't you simply use initializeApp?
import { initializeApp } from "firebase/app";
const config = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
};
export const app = initializeApp(config);
Do you really need your custom initFirebase() function?

Uncaught TypeError: Cannot read property 'initializeApp' of undefined

I'm trying to use a few Firebase libraries in my Vue project (I installed it using npm install firebase).
I added those in main.js:
import { Firebase } from 'firebase/app'
import 'firebase/analytics'
import 'firebase/auth'
import 'firebase/messaging'
Firebase.initializeApp({
apiKey: 'xxx',
authDomain: 'xxx',
databaseURL: 'xxx',
projectId: 'xxx',
storageBucket: 'xxx',
messagingSenderId: 'xxx',
appId: 'xxx',
measurementId: 'xxx'
})
And I get:
Uncaught TypeError: Cannot read property 'initializeApp' of undefined
Change this:
import { Firebase } from 'firebase/app'
into this:
import * as firebase from "firebase/app";
import everything from firebase/app then do:
firebase.initializeApp({
apiKey: 'xxx',
authDomain: 'xxx',
databaseURL: 'xxx',
projectId: 'xxx',
storageBucket: 'xxx',
messagingSenderId: 'xxx',
appId: 'xxx',
measurementId: 'xxx'
})
For newcomers using the newest Firebase Modular API (v9) a refactoring is required.
The imports must be changed to this:
import { FirebaseApp, initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getDatabase } from "firebase/database";
const firebaseConfig = {...}
// Initialize Firebase
const app: FirebaseApp = initializeApp(firebaseConfig);
const db = getDatabase(app);
const auth = getAuth(app);
About this new refactoring style here
And more information on how Read and Write data changed here
Check your Firebase version in your package.json file. If it is 9+ it should be something like this:
import { initializeApp } from "firebase/app";
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
import { getAuth } from "firebase/auth";
and then:
const firebaseConfig = {
apiKey: "...",
authDomain: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
measurementId: "...",
};
// Initialize Firebase
const firebase = initializeApp(firebaseConfig);
const db = getFirestore(firebase);
const auth = getAuth(firebase);
Error that appears caused by the difference of the version you use with the installed SDK version
Simply change from like this :
import { Firebase } from 'firebase/app'
import 'firebase/analytics'
import 'firebase/auth'
import 'firebase/messaging'
to this:
import { Firebase } from 'firebase/compat/app'
import 'firebase/compat/analytics'
import 'firebase/compat/auth'
import 'firebase/compat/messaging'
For clearer info, you can read this SDK9

import firebase.firestore() returns undefined

I have a vue App with vuefire installed. Following the docs here: https://vuefire.vuejs.org/vuefire/getting-started.html#plugin, I have the main.js file :
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { firestorePlugin } from 'vuefire'
Vue.config.productionTip = false;
Vue.use(firestorePlugin);
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
and the firebase.js file like this:
import firebase from "firebase";
const config = {
apiKey: "XXXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
projectId: "XXXXXXX",
storageBucket: "XXXXXX",
messagingSenderId: "XXXXXXX",
appId: "XXXXX"
};
firebase.initializeApp(config);
export const db = firebase.firestore();
And here is the home component
<template>
<div>
<button #click="signIn">Log in with google</button>
</div>
</template>
<script>
import firebase from "firebase";
import db from "#/firebase"
export default {
methods: {
signIn() {
const provider = new firebase.auth.GoogleAuthProvider();
firebase
.auth()
.signInWithPopup(provider)
.then(result => {
const malakas = {
userId: result.user.uid,
email: result.user.email,
displayName: result.user.displayName,
photoURL: result.user.photoURL
};
db.collection("malakes")
.doc(result.user.uid)
.set(spreadOparatorTest, { merge: true });
})
.catch(err => console.log(err));
}
}
};
</script>
<style lang="scss" scoped>
</style>
the weird thing is that in db.collection(...) i get:
TypeError: Cannot read property 'collection' of undefined
because the db that i am importing gets imported as undefined. But if I change the db.collection(...) to firebase.firestore().collection(...) it works fine but i do not understand why.
the problem is that you need to import a few dependencies separately... this is a good safe way:
import firebase from "firebase/app";
require('firebase/firestore')
require('firebase/auth')
const config = {
apiKey: "XXXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
projectId: "XXXXXXX",
storageBucket: "XXXXXX",
messagingSenderId: "XXXXXXX",
appId: "XXXXX"
};
firebase.initializeApp(config);
export const db = firebase.firestore();
export const auth = firebase.auth();
then your components can import em like this:
import firebase from 'firebase/app'
import { db, auth } from "./firebase" // <--- or wherever the config file is
export default {
methods: {
signIn() {
const provider = new firebase.auth.GoogleAuthProvider();
auth
.signInWithPopup(provider)
.then(result => {
const malakas = {
userId: result.user.uid,
email: result.user.email,
displayName: result.user.displayName,
photoURL: result.user.photoURL
};
db.collection("malakes")
.doc(result.user.uid)
.set(spreadOparatorTest, { merge: true });
})
.catch(err => console.log(err));
}
}
};
Hope this helps!

how to intiialize two firebase apps

im trying to initialize two firebase apps but getting an annoying error Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app). Im not sure how to fix this and how to make two seperate firebase. Any help is greatly appreciated!
database instance
import * as firebase from "firebase";
var config = {
apiKey: "AIzaSyC....",
authDomain: "car-app-506db.firebaseapp.com",
databaseURL: "https://car-app-506db.firebaseio.com",
projectId: "car-app-506db",
storageBucket: "car-app-506db.appspot.com",
messagingSenderId: "496521253390"
};
firebase.initializeApp(config);
const databaseRef = firebase.database().ref();
export const CarsRef = databaseRef.child("Cars");
export const authRef = firebase.auth();
export const provider = new firebase.auth.GoogleAuthProvider();
export const timeRef = firebase.database.ServerValue.TIMESTAMP;
export default databaseRef;
auth instance
import firebase from "firebase";
import 'firebase/auth';
import 'firebase/database';
var firebaseConfig = {
apiKey: "AIzaSyC6C-8A-vfsEzv31acwjhru8N64g0Hzhcc",
authDomain: "car-app-506db.firebaseapp.com",
databaseURL: "https://car-app-506db.firebaseio.com",
projectId: "car-app-506db",
storageBucket: "car-app-506db.appspot.com",
messagingSenderId: "496521253390"
};
var app = firebase.initializeApp(app);
export default app;
Each FirebaseApp instance has its own configuration and its own unique name. If you don't specify a name when you initialize the app, Firebase assumes your (re)initializing the default app. Since neither if your calls to firebase.initializeApp specifies a name, you're initializing the same app twice, which is an error.
The solution is to name your apps by passing a name (string) in to the second call to initializeApp. For example:
var firebaseConfig = {
apiKey: "AIzaSyC6C-8A-vfsEzv31acwjhru8N64g0Hzhcc",
authDomain: "car-app-506db.firebaseapp.com",
databaseURL: "https://car-app-506db.firebaseio.com",
projectId: "car-app-506db",
storageBucket: "car-app-506db.appspot.com",
messagingSenderId: "496521253390"
};
var app = firebase.initializeApp(firebaseConfig, "auth");
export default app;
Also see using multiple projects in your application in the Firebase docs.

Categories