import firebase.firestore() returns undefined - javascript

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!

Related

NextAuth and Firebase causing SyntaxError Cannot use import statement outside a module

I'm new to both Next.js and Firebase. I've been trying to use NextAuth.js to authenticate with Discord for my firebase app. However, I ran into an error.
I've tried adding "type": "module" into my package.json file and converting all my imports into requires instead but I still get the same error.
This is my firebase.js
import firebase from "firebase/compat/app";
import { getApps, getApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
import { getStorage } from 'firebase/storage';
export const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID
};
export const app = getApps.length > 0 ? getApp() : firebase.initializeApp(firebaseConfig);
export const firestore = getFirestore(app);
export const storage = getStorage(app);
This is my [...nextauth].js
import NextAuth from "next-auth";
import DiscordProvider from 'next-auth/providers/discord';
import { FirestoreAdapter } from "#next-auth/firebase-adapter";
import { firebaseConfig } from "../../../lib/firebase";
export default NextAuth({
providers: [
DiscordProvider({
clientId: process.env.DISCORD_ID,
clientSecret: process.env.DISCORD_SECRET
}),
],
adapter: FirestoreAdapter(firebaseConfig),
})
Any help would be much appreciated
I went through this as well. I found using a simple config easier and exporting the default app into your component. Then in the component, add the extra functionality.
Here is my config;
import { initializeApp } from 'firebase/app';
// Initialize Firebase
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
}
const app = initializeApp(firebaseConfig)
export default app;
then in controller...
import { getDatabase } from 'firebase/database';
import app from '../services/firebase';
const rtdb = getDatabase(app);

How to solve FirebaseError: Firebase Storage: Invalid URL react native

I couldn't find an answer For Web V9, all I'm trying to do is to delete an image from Firebase-Storage using the URL not the image name as demonstrated in their Docs here
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getDatabase } from "firebase/database";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_KEY,
authDomain: ".....",
databaseURL: ".....",
projectId: ".......",
storageBucket: "......",
messagingSenderId: ".......",
appId: ".......",
measurementId: "......"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const database = getDatabase(app);
export const firestore = getFirestore(app);
export const storage = getStorage(app)
export const auth = getAuth()
So this is the code that I have tried
import { firestore, storage, database } from "../../firebase"
import { deleteObject, ref } from "firebase/storage";
import { storage } from "./firebase";
const SingleApplication = () => {
function delete(){
const ImgUrl = "https://firebasestorage.googleapis.com:443/v0/b/......appspot.com/o/Application-Imeges%2F09........"
const dImgRef = ref(storage, ImgUrl) //ImgUrl is a firebase sotrage url
deleteObject(dImgRef).then(() =>{
console.log("deleted")
})
}
return (
<div className='Main'>
</div>
)
}
export default SingleApplication
and the error was:
Firebase Storage: Invalid URL 'https://firebasestorage.googleapis.com:443/v0/b/......appspot.com/o/Application-Imeges%2F09F501.......'
I'm using react JSX
give permission to delete the file on firebase storage rules
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /folder1/{image} {
allow read: if true
...
allow delete: if true
}
}
}
then
import { deleteObject, ref } from "firebase/storage"
const pathImage = "folder1/image.jpg" // your path
const reference = ref(storage, pathImage)
deleteObject(reference).then().catch()

Uncaught TypeError: _firebase__WEBPACK_IMPORTED_MODULE_1__.default.auth.RecaptchaVerifier is not a constructor

Uncaught TypeError: _firebase__WEBPACK_IMPORTED_MODULE_1__.default.auth.RecaptchaVerifier is not a constructor
This is the error I am getting when I am trying to implement otp verification in my react app
Code
import React, { Component } from 'react'
import db from '../firebase'
export class LooginOTP extends Component {
handleClick=()=>{
var recaptcha = new db.auth.RecaptchaVerifier('recaptcha');
var number = '+xxxxxxxxxxxx';
db.auth().signInWithPhoneNumber(number, recaptcha).then( function(e) {
var code = prompt('Enter the otp', '');
if(code === null) return;
e.confirm(code).then(function (result) {
console.log(result.user);
document.querySelector('label').textContent += result.user.phoneNumber + "Number verified";
}).catch(function (error) {
console.error( error);
});
})
.catch(function (error) {
console.error( error);
});
}
render() {
return (
<div>
<label></label>
<div id="recaptcha"></div>
<button onClick={this.handleClick}>Click</button>
</div>
)
}
}
export default LooginOTP
Here instead of x I am putting my phone number but it is still not coming.
I have also enabled phone verification in my firebase authentication.
My config file :
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
var firebaseApp = firebase.initializeApp({
apiKey: "xxxxxxxxxx",
authDomain: "xxxxxxxxxx",
projectId: "xxxxxxxxxx",
storageBucket: "xxxxxxxxxx",
messagingSenderId: "xxxxxxxxxx",
appId: "xxxxxxxxxx",
measurementId: "xxxxxxxxxx"
});
const db = firebaseApp.firestore();
export { db };
db here is Firestore instance and not auth. Try exporting auth instance as shown below:
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
const RecaptchaVerifier = firebase.auth.RecaptchaVerifier
export { db, auth, RecaptchaVerifier };
Then change your imports to:
// import db from '../firebase'
import { db, auth, RecaptchaVerifier } from '../firebase'
var recaptcha = new RecaptchaVerifier('recaptcha')

Vue: Firebase: Error in mounted hook: "FirebaseError: No Firebase App '[DEFAULT]' has been created

I am building Vue SPA and have checked many posts before posting this.
I am not sure what I am doing wrong.
Below is my App.Vue:
<template>
<div id="app">
<Navigation />
<router-view class="container" :user="user" />
</div>
</template>
<script>
import Navigation from '#/components/Navigation.vue';
// import db from './db.js';
import Firebase from 'firebase';
export default {
name: 'App',
data: function() {
return {
user: null,
};
},
mounted() {
Firebase.auth().onAuthStateChanged(user => {
if (user) {
this.user = user.email;
}
});
},
components: {
Navigation,
},
};
</script>
<style lang="scss">
$primary: #37c6cf;
#import '../node_modules/bootstrap/scss/bootstrap';
</style>
Note: I have commmented the import from db.js which can be find after the first import. If I enable it Vue CLI is throwing different error.
in db.js:
import firebase from 'firebase';
const firebaseConfig = {
apiKey: 'yourkey',
authDomain: 'domainnew.firebaseapp.com',
databaseURL: 'yourdomain.com',
projectId: 'yourproject',
storageBucket: 'test',
messagingSenderId: '454545',
appId: '1:444d96:web:d78df',
measurementId: 'G-69599595',
};
// Initialize firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
firebase.analytics();
export default firebaseApp.firestore();
In the console I am keep getting below two errors and my Vue is not retrieving my email address from Firebase.
Can any one pleas help on this.
The following should do the trick:
db.js file
import firebase from 'firebase/app';
import "firebase/analytics";
import 'firebase/firestore';
import 'firebase/auth';
const firebaseConfig = {
apiKey: 'yourkey',
authDomain: 'domainnew.firebaseapp.com',
databaseURL: 'yourdomain.com',
projectId: 'yourproject',
storageBucket: 'test',
messagingSenderId: '454545',
appId: '1:444d96:web:d78df',
measurementId: 'G-69599595',
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const auth = firebase.auth();
const analytics = firebase.analytics();
export { db, auth, analytics };
App.js file
<template>
<div id="app">
<Navigation />
<router-view class="container" :user="user" />
</div>
</template>
<script>
import Navigation from '#/components/Navigation.vue';
const fb = require('./db.js');
export default {
name: 'App',
data: function() {
return {
user: null,
};
},
mounted() {
fb.auth.onAuthStateChanged(user => {
if (user) {
this.user = user.email;
}
});
},
components: {
Navigation,
},
};
</script>
<style lang="scss">
$primary: #37c6cf;
#import '../node_modules/bootstrap/scss/bootstrap';
</style>

Rewrite firebase service using dynamic import

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 };

Categories