Modular usage of Firebase v9 Beta Library - javascript

Other important information:
Project uses React Library
Initialized with Create React App
This is how my code typically looks like on v8:
// firebase.js
import firebase from "firebase/app";
import "firebase/firestore";
export const app = firebase.initializeApp(config);
export const firestore = app.firestore();
// app.js
import { firestore } from './firebase'
firestore.collection("users").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data()}`);
});
});
I believe with v9, Firebase no longer has that side effect import problem, and so now we explicitly state what functions we want from a package.
// firebase.js
import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'
export const app = initializeApp(config)
export const firestore = getFirestore()
Code below is from Firebase docs
// app.js
import { addDoc, collection } from "firebase/firestore";
try {
const docRef = await addDoc(collection(db, "users"), {
first: "Alan",
middle: "Mathison",
last: "Turing",
born: 1912
});
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
Will the code above (which uses the addDoc and collection imports) refer to the initialized Firestore instance in firebase.js, or is there a proper way to use the initialized Firestore instance?

Firestore instances are managed from the core Firebase App, the firestore modules only include the libraries to make the requests. The solution to getting the Firestore instance without having to reference the core app is to request the instance from the Firestore modules.
import { getFirestore } from 'firebase/firestore';
const db = getFirestore();
Source: https://firebase.google.com/docs/firestore/quickstart#initialize

Related

Firebase v9 Database. ref is not a function?

I've started migrating over to v9 Modular firebase. Please see my config:
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
..
};
const app = initializeApp(firebaseConfig);
// Get a reference to the database service
export const database = getDatabase(app);
Then in another file I made basic CRUD functions.
import { database } from "./firebase"
export const insertTestData = () => {
return database.ref("test").set({name:"hello world"})
}
I got the following error:
Uncaught TypeError: _firebase__WEBPACK_IMPORTED_MODULE_0__.database.ref is not a function
Did I miss anything?
I'm not sure why it's also not picking up imports
You are importing ref() from Modular SDK but still using name-spaced syntax.
Try:
import { getDatabase, ref, set } from "firebase/database";
export const insertTestData = () => {
return set(ref(database, "test"), { name: "hello" })
}
Make sure you are referring to the "Modular" tab of the code snippets in the documentation

firebase auth.sendSignInLinkToEmail method is not working

i installed firebase in react app and initialized like this
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth, GoogleAuthProvider } from "firebase/auth"
// 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
const app = initializeApp(firebaseConfig);
// export
export const auth = getAuth(app);
export const googleAuthProvider = new GoogleAuthProvider();
and imported this file into my react component like this
import {auth} from '../../firebase';
and i try to use it like this
await auth.sendSignInLinkToEmail(email, config);
and it give me this error
In Firebase v9+, you need to use the modular sendSignInLinkToEmail():
import { auth } from '../../firebase';
import { sendSignInLinkToEmail } from "firebase/auth"
await sendSignInLinkToEmail(auth, email, config);
You can catch these errors yourself by familiarizing yourself with the namespaced SDK to modular SDK upgrade process.

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

React Native: firestore/firebase Expected first argument to collection() to be a CollectionReference... how?

So I have a simple React Native app that I created using Expo and debug on my personal Android device.
I've included firebase/firestore into my app and am now trying to add an object to firestore on button click.
Here's my code:
firebaseConfig.js :
import { initializeApp } from '#firebase/app';
var config = {
...
}
const app = initializeApp(config);
export default app;
Component:
import { app } from '../firebaseConfig';
import { getFirestore } from 'firebase/firestore/lite';
import { doc, setDoc, collection, query, where, getDocs, initializeFirestore } from "firebase/firestore";
...
export default function Component() {
const firestoreDb = getFirestore(app);
// this function is called when clicking a button
const onAddListPress = () => {
setDoc(doc(firestoreDb, "cities", "LA"), {
name: "Los Angeles",
state: "CA",
country: "USA"
});
}
}
This throws the following error:
Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
This code above (in the onPress) is copied from the official firestore docs, here:
https://firebase.google.com/docs/firestore/manage-data/add-data#set_a_document
Does anyone have an idea why this does not work?
I suggest you edit your post and remove the firebaseConfig configuration keys, or delete your Firebase app and create a new one from the Firebase console to secure your app. I tried to replicate your application using React, and I received the same error message. There were two changes I made to correct the error. The first one is inside the firebaseConfig file, the default export needs to be changed to a named export:
import { initializeApp } from "firebase/app"
const firebaseConfig = {
//Project configuration keys
};
const app = initializeApp(firebaseConfig);
export { app }; // Change from a default to a named export
In addition, all the imports inside your component should come from the full Javascript SDK, not the lite version. The lite version has some limitations which can result in this specific error.
import { app } from "./firestore-config";
import { getFirestore, getDoc, doc } from "firebase/firestore";
import './App.css';
export default function App() {
const firestoreDB = getFirestore(app);
const docRef = doc(firestoreDB, "users", "testUser1");
const getData = async () => {
const data = await getDoc(docRef);
console.log(data);
}
getData();
return <div className="App"></div>;
}
You might also want to review this GitHub issue if you are using yarn to manage your dependencies.

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