unhandledRejection: ReferenceError: Cannot access 'firestore' before initialization - javascript

I'm very new to next.js, and I'm developing an API with it, side that API I want to use firebase, so I set up firebase but when I try to call it, this error appears: "unhandledRejection: ReferenceError: Cannot access 'firestore' before initialization"
Code below.
Firebase config file
import firebase from 'firebase/app';
import "firebase/firestore";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "*******",
authDomain: "********",
projectId: "*****",
storageBucket: "*****",
messagingSenderId: "****",
appId: "****",
measurementId: "****"
};
//if(!firebase.apps.length){
//}
firebase.initializeApp(firebaseConfig);
const firestore = firebase.firestore();
export { firestore };
Firestore service
import { firestore } from './firebase';
export class Firestore {
async getOne(collection, uid){
const data = await firestore.collection(`${collection}/${uid}`).get();
return await data.docs();
}
}
API page
import {Firestore} from '../../utils/firestore';
const firestore = new Firestore();
const getBanners = () => {
return firestore.getOne('settings','client');
//return data;
}
export default function Handler(req,res){
res.status(200).json({
'name':"getBanners",
'data': getBanners()
});
}

I solved this issue by adding import firebase from 'firebase/compat/app'; and also import 'firebase/compat/firestore';. And works!

Related

Shuffle docs from firebase firestore collection in JavaScript

Randomizing content may be a useful functionality for different applications. The following code completes the task for a firebase firestore collection.
Sample firebase initialization main shuffle code below
// Import Firebase
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-app.js";
import { doc, getDoc, getDocs, collection, getFirestore } from "https://www.gstatic.com/firebasejs/9.5.0/firebase-firestore.js";
// Firebase Config
const firebaseConfig = {
apiKey: "your-info",
authDomain: "your-info",
databaseURL: "your-info",
projectId: "your-info",
storageBucket: "your-info",
messagingSenderId: "your-info",
appId: "your-info",
measurementId: "your-info"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Firestore
const firestore = getFirestore(app);
Code to get a sample 'contributions' collection and console log shuffled docs:
// Get Collection
const contributionsCollection = collection(firestore, 'contributions');
// Get Collection Docs
const contributionsCollectionDoc = await getDocs(contributionsCollection);
// Fill in Contributions
if(contributionsCollectionDoc.empty == false) {
var contributions = contributionsCollectionDoc.docs;
shuffle(contributions);
contributions((doc) => {
console.log(doc.data());
});
}

auth.signInwithPopup is not a function firebase

I am using firebase google authentication to authenticate user using goole.
But i am facing an error which is given below....
(0, _auth.signInWithPopup) is not a function. (In '(0, _auth.signInWithPopup)(auth, provider)', '(0, _auth.signInWithPopup)' is
undefined)
and unable to fix it.
here is my code ...
import statements
import {getAuth,GoogleAuthProvider,signInWithPopup} from "firebase/auth"
the function
const googlelogin=async()=>{
const auth=getAuth()
const provider=new GoogleAuthProvider()
try{
const result=await signInWithPopup(auth,provider)
// const credentials=GoogleAuthProvider.credentialFromResult(result);
// const token=credentials.accessToken
// const user=result.user
}
catch(e){
console.log(e)
}
}
Please tell me how to solve this error...
Thanks in advance
getAuth() function can not be empty. first you should pass the firebase configurations which are can be found on firebase app -> project settings to the initializeApp() function. then pass the results to the getAuth() function.
import {initializeApp} from "firebase/app";
import {getAuth} from 'firebase/auth';
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const firebaseApp = initializeApp(firebaseConfig);
const auth = getAuth(firebaseApp);

Uncaught TypeError: Cannot read property 'GoogleAuthProvider' of undefined cakephp

I am doing a small project with Google authentication. Now, this is my first time doing this, so I might be doing something wrong which I am not seeing. I did the following steps:
-I went on firebase and linked my account
-I enabled google to be able to use it for authentication
-I pasted the project data in my file, as I will show in a bit
-and I put the code for the autentication
<script src="https://www.gstatic.com/firebasejs/7.6.2/firebase-app.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyArVSWB1OYZYQJEkmc6uIi9jyfmRIW1oSk",
authDomain: "assignment-da42d.firebaseapp.com",
databaseURL: "https://assignment-da42d.firebaseio.com",
projectId: "assignment-da42d",
storageBucket: "assignment-da42d.appspot.com",
messagingSenderId: "569189156463",
appId: "",
measurementId: "G-N6D1788RXF"
};
firebase.initializeApp(firebaseConfig);
function googleSignIn(){
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithRedirect(provider)
}
</script>
<button onclick="googleSignIn()">Google Sign in</button>
However, even after following multiple tutorials, using the same methods, I kept getting the error:
Uncaught TypeError: Cannot read property 'GoogleAuthProvider' of undefined
What am I doing wrong please?
I had the same issues late week and I've since solved it.
Can you point out where you include the following or some other version of the auth library?
<script src="/__/firebase/[version number]/firebase-auth.js"></script>
If that's missing you can paste it in before your code.
I installed the whole package - $ npm install --save firebase
and my config file looks like
import firebase from "firebase/app";
import "firebase/storage";
import "firebase/firestore";
import "firebase/auth";
const firebaseConfig = {
apiKey: "......",
authDomain: ".....",
databaseURL: ".....",
projectId: ".....",
storageBucket: ".....",
messagingSenderId: "......",
appId: "......",
measurementId: "...."
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export const projectStorage = firebase.storage();
export const projectFirestore = firebase.firestore();
export const timestamp = firebase.firestore.FieldValue.serverTimestamp;
export const auth = firebase.auth();
export const provider = new firebase.auth.GoogleAuthProvider();
export const signInWithGoogle = () =>{
auth.signInWithRedirect(provider).then(function(){
});
};
and I can call
const logIn = () => {
let ret = signInWithGoogle();
console.log(ret);
getCredentials();
}
in the navbar.

Firebase auth not working using Vue and Vuex

I'm trying to add authentication using Firebase in my Vue app, but I'm getting [Vue warn]: Error in v-on handler: "TypeError: _config_firebase__WEBPACK_IMPORTED_MODULE_8__.user.SignInWithEmailAndPassword is not a function" error.
Here is my irebase config file:
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
const firebaseConfig = {
apiKey: "MY_API_KEY",
authDomain: "MY_AUTH_DOMAIN",
databaseURL: "MY_DB_URL",
projectId: "MY_PROJECT_ID",
storageBucket: "MY_STORAGE_BUCKET",
messagingSenderId: "MY_MESSAGE_SENDER_ID",
appId: "MY_APP_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Get a Firestore instance
export const user = firebase.auth();
export const db = firebase.firestore();
Then the action in Vuex:
import { db, user } from "./config/firebase";
loginUser({ commit }, payload) {
user
.SignInWithEmailAndPassword(payload)
.then(user => {
console.log(user);
commit("SET_USER", user);
})
.catch(error => {
commit("setLoading", false);
commit("setError", error);
console.log(error);
});
router.push("/");
}
So far, I have been able to Create, Read, Update and Delete, although, the config file was slightly different than this, when I added auth was when I altered the code.
Change this:
user.SignInWithEmailAndPassword(payload)
into this:
user.signInWithEmailAndPassword(payload)
From the docs:
Asynchronously signs in using an email and password.

How to enable offline data in firestore for web

I want to enable offline data in my project.
I found the right code for this but I don't know where to implement the code
I implement the code inside the firebaseConfig.js file:
import firebase from 'firebase'
import 'firebase/firestore'
// firebase init
// init code goes here
var config = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: ''
}
firebase.initializeApp(config)
firebase.firestore().enablePersistence()
.then(function () {
// Initialize Cloud Firestore through firebase
var db = firebase.firestore();
})
.catch(function (err) {
console.log(err)
})
// firebase utils
const db = firebase.firestore()
const oldRealTimeDb = firebase.database()
const auth = firebase.auth()
const currentUser = auth.currentUser
// date issue fix according to firebase
const settings = {
timestampsInSnapshots: true
}
db.settings(settings)
// firebase collections
const usersCollection = db.collection('users')
const postsCollection = db.collection('posts')
export {
db,
auth,
currentUser,
postsCollection,
usersCollection
}
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import {store} from './store'
import './registerServiceWorker'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css' // Ensure you are using css-loader
const fb = require('./firebaseConfig.js')
Vue.config.productionTip = false
export const bus = new Vue()
Vue.use(Vuetify)
let app
fb.auth.onAuthStateChanged(user => {
if (!app) {
app = new Vue({
el: '#app',
store,
router,
template: '<App/>',
components: {
App
},
render: h => h(App)
}).$mount('#app')
}
})
I got this error:
The sample code provided in the documentation suggests that you should call enablePersistence() and possibly make note if it fails for some given reason:
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###',
});
firebase.firestore().enablePersistence()
.catch(function(err) {
if (err.code == 'failed-precondition') {
// Multiple tabs open, persistence can only be enabled
// in one tab at a a time.
// ...
} else if (err.code == 'unimplemented') {
// The current browser does not support all of the
// features required to enable persistence
// ...
}
});
Subsequent queries after calling enablePersistence() will be internally queued until it fully completes, which means that the query may or may not be using locally cached data, depending on the result of enablePersistence(). If it's important to your app to be able to use local persistence, you may wish to wait on its result (triggering on the returned promise) before performing the query.
Just remove the second firebase.firestore() and call the enablePersistence as follows:
import firebase from 'firebase'
import 'firebase/firestore'
// firebase init
// init code goes here
var config = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: ''
}
firebase.initializeApp(config)
const db = firebase.firestore();
const auth = firebase.auth();
const currentUser = auth.currentUser;
// date issue fix according to firebase
const settings = {
timestampsInSnapshots: true
};
db.settings(settings);
db.enablePersistence();
// firebase utils
//const db = firebase.firestore() // <---- Remove this line
const oldRealTimeDb = firebase.database()
const auth = firebase.auth()
const currentUser = auth.currentUser

Categories