getting firebase.default.firestore is not a function - reactjs

I am getting this error when I call the onSnapshot listener to listen for changes in the database. I get firebase.default.firestore is not a function.
db.firestore().collection('users').doc(user.id).collection('notifications'), async (snapshot)
db is imported from the file where code is
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
// left empty for the sake of this question
};
const app = initializeApp(firebaseConfig);
export default getFirestore();

Related

Error with Firebase Authentication with react native expo

I get this error: TypeError: (0, _firebase.auth) is not a function. (In '(0, _firebase.auth)()', '(0, _firebase.auth)' is an instance of AuthImpl)
My code is:
`
// Import the functions you need from the SDKs you need
import firebase from 'firebase/compat/app';
import { getAuth } from "firebase/auth";
import AsyncStorage from '#react-native-async-storage/async-storage';
import { initializeAuth, getReactNativePersistence} from 'firebase/auth/react-native';
const firebaseConfig = {
};
// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig);
const auth = initializeAuth(app, {
persistence: getReactNativePersistence(AsyncStorage)
});
export { auth };
`
I tried many variations of imports and different ways for the const auth.

Geofire not recognized on expo

I have an expo project with this firebase config file:
import { initializeApp, getApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import geofire from 'geofire';
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
let firestore = getFirestore(app);
const geofireRef = new geofire(app.database().ref())
export default firestore;
And I'm getting this message when I try to run it:
app.database is not a function. (In 'app.database()', 'app.database' is undefined)
I installed it by running "yarn add geofire"

Uncaught TypeError: firebase_firestore__WEBPACK_IMPORTED_MODULE_3__.doc.data is not a function [duplicate]

This is my first time asking a question on StackOverflow. I am making a school project and I am a beginner at Firebase and JavaScript. I am trying to make a Tinder clone. React is telling me there's an error in this part of my code. At first I had different errors but they were Firebase syntax related and I promptly fixed them but now I don't have a clue on what this error means. My code works on localhost for a split second (I see my application) and then the error appears.
import React, { useEffect, useState } from 'react';
import TinderCard from 'react-tinder-card';
import database from './firebase';
import './SwipeCards.css';
...
function SwipeCards() {
...
useEffect(() => {
database.collection('buddies').onSnapshot((snapshot) => setBuddies(snapshot.docs.map((doc) => doc.data())));
}, []);
...
}
I've tried two solutions of similar problems other people had, namely:
(in my tinderCards.js)
database.firestore().collection('buddies')...
and (in my firebase.js)
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
...
const firebaseApp = initializeApp(firebaseConfig);
const database = getFirestore(firebaseApp);
export default database;
But both didn't work. I can post more of the code if needed. Any help would be greatly appreciated.
You are using the new modular SDK (v9) which no longer uses firebase.firestore() namespace. I'd recommend following the documentation to learn about new syntax:
import database from './firebase';
import { doc, onSnapshot, collection, query, where, onSnapshot } from "firebase/firestore";
useEffect(() => {
const q = query(collection(db, "buddies"))
const unsub = onSnapshot(q, (querySnapshot) => {
console.log("Data", querySnapshot.docs.map(d => doc.data()));
});
}, [])

Stripe and Firebase: FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

I'm trying to setup stripe on my new Firebase app (React). I'm using the new version of Firebase (9) and the new Stripe integration, published 12 days ago:
https://www.npmjs.com/package/#stripe/firestore-stripe-payments
What I'm trying to do here is to load the stripe-hosted checkout for a subscription.
This is the code:
import React, { useEffect } from 'react'
import { createCheckoutSession } from "#stripe/firestore-stripe-payments";
import { payments } from './Firebase'
export default function Stripetest(props) {
async function checkout(e) {
e.preventDefault();
try {
const session = await createCheckoutSession(payments, {
price: "price_1JwyWZIweuKs6S3NBDjBqiiw",
});
window.location.assign(session.url);
} catch (e) {
console.log(e);
}
}
return (
<>
<button onClick={checkout}>Checkout</button>
</>
)
}
This is the Firebase.js that exports "payments":
// 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';
import { getAuth } from 'firebase/auth';
import { getStripePayments } from "#stripe/firestore-stripe-payments";
import { getApp } from "#firebase/app";
// 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 firebaseApp = initializeApp({
apiKey: "AIzaSxxxxxxxxxx",
authDomain: "bxxxxxxxxxx6.firebaseapp.com",
projectId: "bxxxxxxxx6",
storageBucket: "xxxxxxxx.appspot.com",
messagingSenderId: "xxxxxxxxxxxxx",
appId: "1:xxxxxxx",
measurementId: "G-Kxxxxx"
});
export const db = getFirestore(firebaseApp)
export const auth = getAuth(firebaseApp)
export default firebaseApp;
const app = getApp();
export const payments = getStripePayments(app, {
productsCollection: "products",
customersCollection: "customers"
});
I've tried both "app" and "firebaseApp" in "getStripePayments(APP, {" but when I click the checkout button it's always the same error:
FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
I downgraded from:
"#stripe/firestore-stripe-payments": "0.0.4",
to
"#stripe/firestore-stripe-payments": "0.0.3",
in package.json and the bug stopped occurring and all works fine now

Authentication with Firebase and Cloud Firestore

I am trying to figure out how to add authentication to a react app that uses Cloud Firestore rather than Realtime Database.
I followed this tutorial and got the whole thing working. Then - the change I'm trying to add is the move from Realtime Database to Cloud Firestore - this makes a difference to whether authentication works. I have made 20 new projects to try to get this work - totally without the process in the tutorial and just relying on firebase documentation. None of them work.
Currently, I have a config file with:
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import firestore from "firebase/firestore";
class Firebase {
constructor() {
app.initializeApp(config).firestore();
this.auth = app.default.auth();
// this.db = app.firebase.database()
this.db = app.firestore();
}
Then, i have a form with this submit handler:
import Firebase from '../../../firebase.1';
handleCreate = () => {
const { form } = this.formRef.props;
form.validateFields((err, values) => {
if (err) {
return;
};
const payload = {
// ...values,
name: values.name,
email: values.email,
organisation: values.organisation,
beta: values.beta,
role: values.role,
// createdAt: Firebase.FieldValue.serverTimestamp()
}
console.log("formvalues", payload);
Firebase
.auth()
.createUserWithEmailAndPassword(values.email, values.password)
console.log('Received values of form: ', values);
Firebase
.collection("users")
.add(payload)
// .then(docRef => {
// resetForm(initialValues);
// })
.then(e => this.setState({ modalShow: true }))
form.resetFields();
this.setState({ visible: false });
this.props.history.push(DASHBOARD);
});
};
At the moment, when I console.log(Firebase) I get:
Uncaught ReferenceError: Firebase is not defined
I have seen this post and followed each one of the recommendations in all of the answers.
I have tried changing the config file uses:
this.auth = app.default.auth();
It makes no difference.
When I try to use this, i get an error that says:
TypeError: _firebase_1__WEBPACK_IMPORTED_MODULE_14__.default.auth is not a function
Does anyone know how to use auth with firebase - where there is a Cloud Firestore instead of a Realtime Database - it's so weird that this makes a difference to whether the authentication tool works.
I've turned off the timestamp entry because I can't get firestore to record that either - but that is a problem for another day. I'm really trying to figure out how to use the authentication tool for now.
NEXT ATTEMPT
I tried to change the firebase.js file so that the config now looks like this:
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
const devConfig = {
};
const prodConfig = {
};
const config =
process.env.NODE_ENV === 'production' ? prodConfig : devConfig;
const Firebase = app.initializeApp(config);
const database = app.firestore();
const auth = app.auth();
const settings = { timestampsInSnapshots: true };
export { Firebase, database as default, settings, auth };
Now, I get an error that says:
TypeError: _components_firebase__WEBPACK_IMPORTED_MODULE_2__.default
is not a constructor
I have been googling - what is a constructor. What is a webpack imported module number reference etc for the last few hours. I would love to know how to translate these error messages into something understandable.
Googling this exact error message suggests that something is wrong with the way the import and export statements are made. The new export in firebase.js is unusual (but others on Stack Overflow have tried it with problems using Firebase). It's still a question mark for me because I don't understand what the error message means.
The error message points to this line of my src/index.js
ReactDOM.render(
<FirebaseContext.Provider value={new Firebase()}>
That line comes from:
import FirebaseContext, { withFirebase } from './Context';
import Firebase from '../../firebase.1';
export default Firebase;
export { FirebaseContext, withFirebase };
That file imports from:
import React from 'react';
const FirebaseContext = React.createContext(null);
export const withFirebase = Component => props => (
<FirebaseContext.Consumer>
{firebase => <Component {...props} firebase={firebase} />}
</FirebaseContext.Consumer>
);
export default FirebaseContext;
It would be a huge reveal if anyone has any advice for learning how to learn what error messages mean. For the moment I'm guessing.
I just finished the tutorial recently also, but I simplified my firebase file. I export only the reference to the initialised firebase
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
const config = {
//...
};
const firebase = app.initializeApp(config);
export default firebase;
And in my project I have:
//...
import firebase from '../../firebase';
//...
useEffect(() => {
const listener = firebase
.firestore()
.collection(COLLECTIONS.USERS)
.onSnapshot(querySnapshot => {
setUsers(querySnapshot);
querySnapshot.forEach(doc => console.log(doc.id, doc.data()));
});
return listener;
}, []);
//...
Check out my Github project here -> https://github.com/henev/react-auth-with-firebase

Resources