getApp is not defined - javascript

I'm using firebase for a SvelteKit project. I'm getting the following error only after reloading:
getApp is not defined
from the file /src/routes/admin/index.svelte:
import { initializeApp, getApps, getApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
// (config info)
};
const firebaseApp =
(getApps().length === 0 ? initializeApp(firebaseConfig) : getApp());
const db = getFirestore();
const colRef = collection(db, "questions");
Why does firebase work until I reload? I'm guessing it's something to do with the fact that only the first page load is server rendered? Does getApp() not work on the client?

Related

Firestore get count for a collection not working

I have this code:
import { getCountFromServer } from 'firebase/firestore'
useEffect(()=> {
const getCount = async () => {
const collection = userDB().collection('invoices')
const query = collection.where('status', '==', 'paid')
const snapshot = await getCountFromServer(query)
setCount(snapshot.data().count)
}
getCount().catch(err=> console.log(err))
}, [user, collectionRef, filterKey, filterValue])
Where userDB() is the same as db.collection('users').doc(userid')
Yet this throughs an error:
TypeError: Cannot read properties of undefined (reading '_t')
at gn (index.esm2017.js:4251:1)
at bu (index.esm2017.js:13685:1)
at Ca.run (index.esm2017.js:16797:1)
at index.esm2017.js:20050:1
I have followed the docs: https://firebase.google.com/docs/firestore/query-data/aggregation-queries#web-version-9_1
Currently using:
"firebase": "^9.15.0",
userDB is defined in a ts file like so:
export const userDB = () => {
let user = auth.currentUser
return db.collection('users').doc(user?.uid)
}
Here is the initlizer file:
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
import 'firebase/compat/auth';
const firebaseApp = firebase.initializeApp ({
...keys
});
export const Providers = {
google: new firebase.auth.GoogleAuthProvider(),
};
const db = firebaseApp.firestore()
const auth = firebase.auth();
const Fire = firebaseApp
export {db, Fire, auth}
You should not uses both compat and modular SDKs together. The compat version does not support count queries. I would recommend updating your code to use the new syntax:
import { initializeApp } from 'firebase/app';
import { getFirestore } 'firebase/firestore';
import { getAuth, GoogleAuthProvider } 'firebase/auth';
const firebaseApp = initializeApp({
...keys
});
export const Providers = {
google: new GoogleAuthProvider(),
};
const db = getFirestore()
const auth = getAuth();
export { db, auth }
import { db } from '...'
import { collection, query, where, getCountFromServer } from 'firebase/firestore'
useEffect(()=> {
const getCount = async () => {
const q = query(collection(db, 'invoices'), where('status', '==', 'paid'))
const snapshot = await getCountFromServer(q)
setCount(snapshot.data().count)
}
getCount().catch(err=> console.log(err))
}, [user, collectionRef, filterKey, filterValue])

How to set useState by checking User data in Firebase

I can't seem to figure out how to set useState after querying Firebase.
I need BOX to be equal to "public URL" for everyone except for admin.
import { auth } from "../firebase";
...
const [BOX, setBox] = useState('');
useEffect(() => {
if (auth.currentUser?.email === "admin#yahoo.com") {
setBox("https://admin/link");
} else {
setBox("https://public/link");
}
},[auth]);
Errors are always different. Sometimes it returns "...empty link", sometimes "network request failed". Sometimes it does show the correct data, but it runs into one of the errors when I refresh the screen.
Here is my firebase file
// Import the functions you need from the SDKs you need
import * as firebase from "firebase";
import 'firebase/firestore';
// 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 = {
...
};
// Initialize Firebase
let app;
if (firebase.apps.length === 0) {
app = firebase.initializeApp(firebaseConfig);
} else {
app = firebase.app()
}
const auth = firebase.auth();
const dbFirebase = app.firestore();
export {auth, dbFirebase};
You can not use hook inside an if statement...
const [box, setBox] = useState('');
useEffect(() => {
if (auth.currentUser?.email === "admin#yahoo.com") {
setBox("https://admin/link");
} else {
setBox("https://public/link");
}
},[auth]);
For firebase 9 you will need to configure it like below:
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
const firebaseConfig = {...}
initializeApp(firebaseConfig)
export const auth = getAuth()

Firebase Question - Uncaught TypeError: firebaseApp.firestore is not a function

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
const firebaseConfig = {
projectId: "projectId"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebase.auth();
export { db, auth };
To fix your error, you need to add import 'firebase/compat/firestore' under your import statements. Also, check the documentation to update imports to v9 compat.
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseConfig = {
...
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebase.auth();
export { db, auth };
You first need to import Firestore SDK to use it. Try adding the following import below auth:
import "firebase/compat/firestore"

TypeError: firebaseApp.firestore is not a function. while trying to use it in a Reactjs Project

hello first time posting so i have been struggling with this error and tried fix of others here and it didnt work here is my firebase_init.js code:
import * as firebase from "firebase/app";
const firebaseConfig = {
apiKey: ""
authDomain:""
projectId:""
storageBucket:""
messagingSenderId:""
appId:""
measurementId:""
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
export { db, auth };
And after checking documentation i copied these codes to index.html in the public folder of the react project:
<script defer src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
<script defer src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
// ...
<script defer src="../src/firebase-init.js"></script>
still nothing worked, tried different imports, i also tried deleting node modules and package-lock.json and reinstalling, it just ended up messing up a whole lot of stuff in the node modules, so that didn't work either. So any help to solving this will be appreciated.
Update your firebase file to include the imports for the services you are planning to use. The script references may simply not be available at the time you are attempting to initialize auth and firestore:
import firebase from "firebase/app";
// static import of firestore
import "firebase/firestore";
// static import of auth
import "firebase/auth";
const firebaseConfig = {
apiKey: ""
authDomain:""
projectId:""
storageBucket:""
messagingSenderId:""
appId:""
measurementId:""
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
export { db, auth };
Keep in mind, this is for version 8 of firebase. The newer version at the time of this answer, version 9, will look pretty different:
import { initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore/lite';
import { getAuth } from 'firebase/auth';
const firebaseConfig = {
apiKey: ""
authDomain:""
projectId:""
storageBucket:""
messagingSenderId:""
appId:""
measurementId:""
};
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
const auth = getAuth(db);
export { db, auth };

Firebase Reactjs - ae.collection is not a function

I can't figure out what is the error here. I made the tutorial Firebase/website and did the same things in my project. I am trying to print out the collection I created on Firebase in my React website but got the error at the line db.collection : Uncaught (in promise) TypeError: ae.collection is not a function
component.js :
// React
import { useState, useEffect } from "react";
import { db, collection, getDocs } from '../../../firebase.js';
const [holder, setHolder] = useState([]); // update
db.collection("holder").onSnapshot((snapshot) => {
setHolder(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
);
});
console.log({ holder });
update : firebase.js below
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
// 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
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
...
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
export const db = getFirestore(app);
Thank you !
You are using Firebase Modular SDK which has a completely new syntax and you must use the same in your code. Try refactoring the code to this:
// React
import { useState, useEffect } from "react";
import { db } from '../../../firebase.js';
import { onSnapshot, collection } from 'firebase/firestore'
const [holder, setHolder] = useState([]); // update
onSnapshot(collection(db, 'holder'), (snapshot) => {
setHolder(
snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
);
})
Also make sure your getFirestore import is from firebase/firestore and not from lite in firebase.js or you'll run into this issue:
import { getFirestore } from 'firebase/firestore';

Categories