error - ReferenceError: Cannot access 'auth' before initialization - reactjs

so I am following this online tutorial on how to build a WhatsApp build and I ran into this problem.
import "../styles/globals.css";
import { useAuthState } from "react-firebase-hooks/auth";
import { auth, db } from "../firebase";
function MyApp({ Component, pageProps }) {
const [user] = useAuthState(auth);
if (!user) return <Login />;
return <Component {...pageProps} />;
}
export default MyApp;
This is my firebase.js, I removed the my apiKey because I am sharing my code but that don't think that is the issue.
import firebase from "firebase/app";
const firebaseConfig = {
apiKey: "",
authDomain: "global-chat-80ab3.firebaseapp.com",
projectId: "global-chat-80ab3",
storageBucket: "global-chat-80ab3.appspot.com",
messagingSenderId: "405392556419",
appId: "1:405392556419:web:562d012b108561b8be76b6",
};
const app = !firebase.apps.length
? firebase.initializeApp(firebaseConfig)
: firebase.app();
const db = app.firestore();
const auth = app.auth();
const provider = new firebase.auth.GoogleAuthProvider();
export { db, auth, provider };

I'm using firebase v9 modular code as in firebase Documentation
Firebase Version: 9.6.1
This code worked fine for me. But the downside I faced was v9 modular functionalities won't work with react-firebase-hooks.(Not supported till now I guess)
My usecase: for next.js project with firebase.
import { initializeApp, getApps } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";
import { GoogleAuthProvider } from "firebase/auth";
const firebaseConfig = {
apiKey: "",
authDomain: "global-chat-80ab3.firebaseapp.com",
projectId: "global-chat-80ab3",
storageBucket: "global-chat-80ab3.appspot.com",
messagingSenderId: "405392556419",
appId: "1:405392556419:web:562d012b108561b8be76b6",
};
// Initialize Firebase
const app = getApps().length === 0 ? initializeApp(firebaseConfig) : getApps();
const auth = getAuth();
const db = getFirestore();
const provider = new GoogleAuthProvider();
export { db, auth, provider };

If you're using Firebase 9.6.0, try updating your imports to v9 compat. This recommendation comes from the Firebase documentation.
So, your imports would look like this:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseConfig = {
apiKey: "",
authDomain: "global-chat-80ab3.firebaseapp.com",
projectId: "global-chat-80ab3",
storageBucket: "global-chat-80ab3.appspot.com",
messagingSenderId: "405392556419",
appId: "1:405392556419:web:562d012b108561b8be76b6",
};
const app = !firebase.apps.length
? firebase.initializeApp(firebaseConfig)
: firebase.app();
const db = app.firestore();
const auth = app.auth();
const provider = new firebase.auth.GoogleAuthProvider();
export { db, auth, provider };

Related

Firebase Cloud Messaging Error: Service messaging is not available

I have firebase installed (previously working with Auth, Firestore, Storage, with no problems) but when I want to implement messaging I have this error message:
Error: Service messaging is not available
Working with Next.js.
This is my firebase.js config file:
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getMessaging } from "firebase/messaging";
const firebaseConfig = {
apiKey: "--------------------",
authDomain: "------------------",
projectId: "--------------------",
storageBucket: "--------------------",
messagingSenderId: "------------------------",
appId: "---------------------------",
measurementId: "--------------------",
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth();
export const db = getFirestore(app);
export const messaging = getMessaging(app);
I have already reinstalled firebase with version 9.15.0

I am getting this error - FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists with different options or config (app/duplicate-app)

import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID
}
const app = initializeApp(firebaseConfig)
export const auth = getAuth()
export const db = getFirestore(app)
console.log('db', db)
I have tried the length thing but it doesn't seem to work with firebase v9. i need to export the db too.
without connecting to the db, the app works just fine.
After lot of trial and error figured out :)
import * as firebase from "firebase/app";
import { logEvent } from "firebase/analytics";
import { getAnalytics } from "firebase/analytics";
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
appId: process.env.APP_ID,
measurementId: process.env.MEASUREMENT_ID
};
let app;
if (!firebase.getApps().length) {
app = firebase.initializeApp(firebaseConfig);
} else {
// if already initialized, use that one
app = firebase.getApp();
}
export function analyticsLogEvents(event:string, params:any) {
let analytics;
if (typeof window !== "undefined") {
analytics = getAnalytics(app);
logEvent(analytics, event, params);
}
}

I am learning reactjs. So as I was into firebase config and after I finished I got a blank react screen

after i have installed these:
npm install firebase
npm install firebase-tools
This was my firebase file before
import firebase from "firebase";
const firebaseConfig = {
apiKey: "AIzaSyA9BnlX96fMf7XiUVCFRsoQzG8DGERJkeY",
authDomain: "disneyplus-clone-a33d5.firebaseapp.com",
projectId: "disneyplus-clone-a33d5",
storageBucket: "disneyplus-clone-a33d5.appspot.com",
messagingSenderId: "37918794208",
appId: "1:37918794208:web:dbe9842dfe1dda522a4b85",
measurementId: "G-DRVLJKWRWG",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
const storage = firebase.storage();
export { auth, provider, storage };
export default db;
THIS IS WHERE IM TRING TO USE IT
import React, {useEffect} from 'react';
import styled from 'styled-components';
import ImgSlider from './ImgSlider';
import Viewers from './Viewers';
import Movies from './Movies';
import { db } from '../firebase';
import Detail from './Detail';
function Home() {
useEffect(() => {
db.collection("movies").onSnapshot((snapshot)=>{
console.log(snapshot);
})
}, [])
After doing some searches, I was advised to change to firebase v9.12.1, of which it changed my firebase file to look like this:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseConfig = {
apiKey: "AIzaSyA9BnlX96fMf7XiUVCFRsoQzG8DGERJkeY",
authDomain: "disneyplus-clone-a33d5.firebaseapp.com",
projectId: "disneyplus-clone-a33d5",
storageBucket: "disneyplus-clone-a33d5.appspot.com",
messagingSenderId: "37918794208",
appId: "1:37918794208:web:dbe9842dfe1dda522a4b85",
measurementId: "G-DRVLJKWRWG",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
const storage = firebase.storage();
export { auth, db, provider, storage };
I am still getting the blank react screen, what might be the problem, or what am I not grasping? Thanks.

Reactjs Firebase: Uncaught TypeError: (0 , _config_firebase__WEBPACK_IMPORTED_MODULE_2__.default) is not a function

I'm pretty new to react and firebase. I implemented a login/auth system with firebase, and I was trying to take this to the next level: implement a profile page with profile picture. I followed a youtube tutorial and it seemed pretty easy,but somehow I'm getting a firebase error, and I assume something changed since the release of that tutorial! I don't really know what is going on, please help me fix this and explain me like I'm 5!
(update profile picture file)
ProfilePicture.js:
import React, {useEffect, useState} from 'react'
import {useAuth} from '../authentication/AuthContext'
import upload from '../../config/firebase'
export default function ProfilePicture() {
const currentUser = useAuth()
const [photo, setPhoto] = useState(null)
const [loading, setLoading] = useState(false)
const [photoURL, setPhotoURL] = useState("https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png")
function handleChange(e){
if (e.target.files[0]){
setPhoto(e.target.files[0])
}
}
function handleClick(){
upload(photo, currentUser, setLoading)
}
useEffect(()=>{
if (currentUser && currentUser.photoURL){
setPhotoURL(currentUser.photoURL)
}
}, [currentUser])
return (
<>
<input type="file" onChange={handleChange} />
<button disabled={loading || !photo} onClick={handleClick}>Upload</button>
<img src={photoURL} alt="Avatar" className='avatar'/>
</>
)
}
firebase.js
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/firestore'
import { getStorage, ref, uploadBytes } from 'firebase/storage';
const app = firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
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
})
export const auth = firebase.auth();
export const firestore = firebase.firestore();
export const storage = getStorage();
//storage
export async function upload(file, currentUser, setLoading){
const fileRef = ref(storage, currentUser.uid + '.png')
setLoading(true)
const snapshot = await uploadBytes(fileRef, file)
setLoading(false)
alert("Uploaded File!")
}
export const createUserDocument = async (user, additionalData) => {
if (!user) return;
const userRef = firestore.doc(`users/${user.uid}`);
const snapshot = await userRef.get();
if (!snapshot.exists) {
const { email } = user;
const { displayName } = additionalData;
try {
await userRef.set({
displayName,
email,
createdAt: new Date(),
});
} catch (error) {
console.log('Error creating user', error);
}
}
};
export default app
the error:
You are mixing up firebase compat version with the latest firebase modular version
The following lines are not needed.
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/firestore'
https://firebase.google.com/docs/web/modular-upgrade
You may want to revisit the documentation, and only follow the codes under version 9 modular.
For example, to initialize the app, the correct codes for version 9 modular will be something like this.
import { initializeApp, getApps } from "firebase/app"
var firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECTID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGEBUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID
};
For authentication you need to use getAuth
For example
import firebase from 'src/firebase/firebase'
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";
const auth = getAuth(firebase);
export async function loginPassword(email, password) {
return await signInWithEmailAndPassword(auth, email,password)
}
Reference: https://firebase.google.com/docs/auth/web/password-auth
Please follow the codes from v9 modular

TypeError: _firebase_js__WEBPACK_IMPORTED_MODULE_1__.default.auth is not a function

Can someone explain this error to me with the context to my code if possible. Written in React.js for user authentication using firebase:
import React, { useEffect, useState } from "react";
import firebaseConfig from "./firebase.js";
export const AuthContext = React.createContext("");
export const AuthProvider = ({ children }) => {
const [loading, setLoading] = useState(true);
const [currentUser, setCurrentUser] = useState(null);
useEffect(() => {
firebaseConfig.auth().onAuthStateChanged((user) => {
setCurrentUser(user);
setLoading(false);
});
}, []);
if (loading) {
return <p>Loading...</p>;
}
return (
<AuthContext.Provider value={{ currentUser }}>
{children}
</AuthContext.Provider>
);
};
The firebase.js file looks something like this:
import firebase from "firebase/app";
import "firebase/auth";
const firebaseConfig = firebase.initializeApp({
apiKey: "*******************************",
authDomain: "react-firebase-auth-****.firebaseapp.com",
databaseURL: "https://react-firebase-auth-****.firebaseio.com",
projectId: "react-firebase-*******",
storageBucket: "react-firebase********.appspot.com",
messagingSenderId: "**********",
appId: "****************************",
});
export default firebaseConfig;
Sounds like you’re trying to call it before it’s imported/loaded.
Please, could you modify your firebase.js file and use my code:
Note: I changed the way to import firebase
import firebase from "firebase"; //noted this
import "firebase/auth";
const firebaseConfig = firebase.initializeApp({
apiKey: "*******************************",
authDomain: "react-firebase-auth-****.firebaseapp.com",
databaseURL: "https://react-firebase-auth-****.firebaseio.com",
projectId: "react-firebase-*******",
storageBucket: "react-firebase********.appspot.com",
messagingSenderId: "**********",
appId: "****************************",
});
//noted this
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
} else {
firebase.app(); // if already initialized, use that one
}
export { firebase } //noted this
Try exporting Firebase services individually like this instead of exporting everything:
import firebase from 'firebase/app';
import 'firebase/auth';
const firebaseConfig = {...};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
const auth = firebase.auth();
export {auth}
Importing and usage:
import {auth} from "./firebase"
auth.onAuthStateChanged((user) => {...})

Resources