All works ok, sign in, signup, even the database, but when I am trying to sign out this error show up:
[TypeError: undefined is not an object (evaluating
'_$$_REQUIRE(_dependencyMap[0],
"#firebase/util").getModularInstance(auth).signOut')]
This is my firebase file:
import { initializeApp, getApps} from 'firebase/app';
import {initializeAuth, getAuth} from 'firebase/auth';
import { initializeFirestore } from 'firebase/firestore';
import { getReactNativePersistence } from 'firebase/auth/react-native';
import AsyncStorage from '#react-native-async-storage/async-storage';
import {REACT_APP_APIKEY,
REACT_APP_AUTHDOMAIN,
REACT_APP_PROJECTID,
REACT_APP_STORAGEBUCKET,
REACT_APP_MESSAGINGSENDERID,
REACT_APP_APPID
} from "#env"
// Firebase config
const firebaseConfig = {
apiKey: REACT_APP_APIKEY,
authDomain: REACT_APP_AUTHDOMAIN,
projectId: REACT_APP_PROJECTID,
storageBucket: REACT_APP_STORAGEBUCKET,
messagingSenderId: REACT_APP_MESSAGINGSENDERID,
appId: REACT_APP_APPID,
};
// initialize firebase
let firebaseApp;
let auth;
if (getApps().length < 1) {
firebaseApp = initializeApp(firebaseConfig);
auth = initializeAuth(firebaseApp, {
persistence: getReactNativePersistence(AsyncStorage),
});
} else {
auth = getAuth();
}
export default auth;
export const database = initializeFirestore(firebaseApp, {
experimentalForceLongPolling: true,
});
This is when I am calling the function:
import { signOut } from 'firebase/auth';
import {database, auth} from '../config/firebase';
const onSignOut = () => {
try {
signOut(auth).then(()=> console.log("signout"))
} catch (error) {
console.log('Error logging out: ', error)
}
};
I finally found the problem, it was my mistake.
As you can see in my firebase file, I export the "auth" as default, but when I am trying to import it, I am importing inside the curly braces {auth}, but It must be outside due it is default. I fixed that and the problem is fixed.
this is the right way:
import auth, {database} from '../config/firebase';
Related
I am using NextJS and Firebase fairly new to both. My app is trying to collect data from firestore database on some occasions it works fine and sometimes it returns "n is undefined" refering to the firestore object "db". This happens when i call the "collection(db, "users", uid, "posts")" function in the [posts].js file. What is causing this?
Firebase.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import {getStorage} from "firebase/storage"
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const storage = getStorage(app);
export const db = getFirestore(app);
[posts].js
import { useRouter } from 'next/router'
import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useAuth } from '../context/AuthContext'
import styles from '../styles/dashboard.module.css';
import Image from 'next/image';
import { collection, getDocs } from "firebase/firestore";
import { db } from '../lib/firebase';
export default function Posts(){
const [queriedData, setQueriedData] = useState([]);
const router = useRouter()
const { uid } = router.query
useEffect(() => {
async function fetchData() {
const postsRef = collection(db, "users", uid, "posts");
const snapshot = await getDocs(postsRef);
const postData = snapshot.docs.map((doc) => {
const data = doc.data();
data.id = doc.id;
return data;
});
setQueriedData(postData);
}
fetchData();
}, []);
return(
{queriedData.map((post) =>(<div>post.title</div>)
)}
}
Added await to the collection function and I also thought it was internet issues hence i setup a firebase emulator still got the same behavior.
I tried console logging "db" right after the line "export const db = getFirestore(app);". I got out "[Object Object]"
I am following these firebase docs : https://firebase.google.com/docs/auth/web/passing-state-in-email-actions
I am using: React 18.2.0, firebase 11.4.2
I am wanting to pass state in email actions when I send a user an email verification request.
My issue here is that I do not know how to obtain the firebase object as in this documention code:
firebase.auth().currentUser.sendEmailVerification(actionCodeSettings)
.then(function() {
// Verification email sent.
})
.catch(function(error) {
// Error occurred. Inspect error.code.
});
I have my firebase.js file configured this way:
import { initializeApp } from "firebase/app";
import { getAuth } from 'firebase/auth';
import { getFirestore } from "firebase/firestore";
import { getStorage } from 'firebase/storage';
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGINGSENDERID,
appId: process.env.REACT_APP_APP_ID
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = getAuth();
export const storage = getStorage(app);
I have tried:
auth.currentUser.sendEmailVerification(actionCodeSettings)
And I have also tried (in my firebase.js):
import firebase from 'firebase/app';
but to no avail...where am I going wrong in obtaining this firebase object?
Not sure why I am getting this error, here's my setup. this error only happens for firestore. Auth, functions, storage, realtimedb work not sure what I'm missing. I followed The firebase documentation to set up.
firebase.js
import { initializeApp } from "firebase/app";
import { initializeAppCheck, ReCaptchaV3Provider } from "firebase/app-check";
import { getDatabase, connectDatabaseEmulator } from "firebase/database";
import {
getAuth,
connectAuthEmulator,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
} from "firebase/auth";
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
import {
getFunctions,
connectFunctionsEmulator,
httpsCallable,
} from "firebase/functions";
import { getStorage, connectStorageEmulator } from "firebase/storage";
import Constants from "expo-constants";
// Initialize Firebase
const firebaseConfig = {
apiKey: Constants.manifest.extra.apiKey,
authDomain: Constants.manifest.extra.authDomain,
dataBaseURL: Constants.manifest.extra.databaseURL,
projectId: Constants.manifest.extra.projectId,
storageBucket: Constants.manifest.extra.storageBucket,
messagingSenderId: Constants.manifest.extra.messagingSenderId,
appId: Constants.manifest.extra.appId,
};
const app = initializeApp(firebaseConfig);
export const firestore = {
instance: () => {
return getFirestore(app);
},
connectFirestoreEmulator: (host, port) => {
return connectFirestoreEmulator(getFirestore(app), host, port);
},
};
if (__DEV__) {
try {
firestore.connectFirestoreEmulator("localhost", "8080");
console.log("====================================");
console.log("connected to emulators....");
console.log("====================================");
} catch (error) {
console.log("====================================");
console.log(error, "error connectiong emulators");
console.log("====================================");
}
}
Since you mentioned that the error seems to happen only in Firestore, I have followed the documentation related to using the Firestore emulator, and my app successfully connects to the local emulator and retrieves local data.
I’m not sure if the way you export the Firestore instance is causing the issue, but the documentation shows that the function must be imported and used, passing the Firestore instance as an argument. This is the sample code I tested:
firestore-config.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
// Configuration keys
};
const app = initializeApp(firebaseConfig);
export const firestore = getFirestore(app);
app.js
import { firestore } from "./firestore-config";
import { getDoc, doc, connectFirestoreEmulator } from "firebase/firestore";
import "./App.css";
export default function App() {
try{
connectFirestoreEmulator(firestore, "localhost", "8080");
console.log("connected");
const docRef = doc(firestore, "localTest", "localTestDoc");
const getData = async () => {
const docSnap = await getDoc(docRef);
console.log(docSnap.data());
}
getData();
}
catch(err){
console.log("error: ", err)
}
return <div className="App"></div>;
}
I am able to see my data coming from the emulated Firestore as output. It would also be useful to see a full error stack trace, since the error from the title is not really that descriptive.
I am new to both Firebase and React so bear with me here.
I am trying to use cloud Firestore and Authentication in my application but am a little unsure on how to set up my firebase.js file. I have scaled the internet and watched plenty of videos/tutorials but can't seem to figure out how to implement these into my app. It also seems that some tutorials that I watched from 2020 are not out of date.
Here's my code:
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// import { getAuth, signInWithCustomToken } from "firebase/auth";
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID
};
// const auth = getAuth();
// signInWithCustomToken(auth, token)
// .then((userCredential) => {
// // Signed in
// const user = userCredential.user;
// // ...
// })
// .catch((error) => {
// const errorCode = error.code;
// const errorMessage = error.message;
// // ...
// });
const app = initializeApp(firebaseConfig);
const db = getFirestore(app)
// export const auth = app.auth()
export { db }
You can export the auth instance from firebase.js and then use it in any component you need. Assuming you have a login component:
firebase.js:
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth"
const app = initializeApp(firebaseConfig);
const db = getFirestore(app)
const auth = getAuth(app)
export { db, auth }
login.jsx:
// login component
import { auth } from "./firebase.js"
import { signInWithEmailAndPassword } from "firebase/auth"
// run on button click or relevant events
signInWithEmailAndPassword(auth, email, password).then((user) => {
console.log(user)
})
I'm building a react app, and I want to integrate google signin using firebase. I've followed the firebase documentation in implementing it, yet I keep getting this error - "TypeError: firebase.auth.GoogleAuthProvider is not a constructor".
Here's my code;
firebase.prod.js
import Firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
import "firebase/storage";
const config = {
apiKey: "AIzaSyASOat6CaIWxzwnepoGBHDpltnf9jH1QH0",
authDomain: "cv-builder-c0429.firebaseapp.com",
databaseURL: "https://cv-builder-c0429.firebaseio.com",
storageBucket: "cv-builder-c0429.appspot.com",
};
const firebase = Firebase.initializeApp(config);
export { firebase };
signin.js
import React, { useState, useContext } from "react";
import { FirebaseContext } from "../context/firebase";
export default function SignUp() {
const { firebase } = useContext(FirebaseContext);
const googleSignIn = () => {
var provider = new firebase.auth.GoogleAuthProvider();
provider.addScope('profile');
provider.addScope('email');
firebase.auth()
.signInWithPopup(provider)
.then((result) => {
console.log(result)
}).catch((error) => {
console.log(error);
});
};
return (
<button onClick={googleSignIn}>Sign in with google</button>
)
};
Any help in fixing this will be appreciated.