React Native authentication and cloud Firestore for web apps - reactjs

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

Related

firestore not creating document with setDoc

When i add new user on my firebase database, it is created successfully on authentication and his profil picture is added successfully on the storage. The successuful toast is appearing. But the document with his informations is not created. i'm using the setDoc method to create de document.
It's a react app.
Help me please
firebase.config.js
import { initializeApp } from "firebase/app";
import { getAuth } from 'firebase/auth'
import { getStorage } from 'firebase/storage'
import { getFirestore } from 'firebase/firestore'
const firebaseConfig = {
apiKey: "AIzaSyCsnZPoO6LIhvXwxjKkJe60AvmkgNqYhqM",
authDomain: "le-prof-e863b.firebaseapp.com",
projectId: "le-prof-e863b",
storageBucket: "le-prof-e863b.appspot.com",
messagingSenderId: "433335960615",
appId: "1:433335960615:web:650aa77f403efff66f3a02",
measurementId: "G-6N2HDEQVXV"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app)
export const db = getFirestore(app)
export const storage = getStorage(app)
export default app
Signup.jsx
import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth";
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { setDoc, doc } from 'firebase/firestore';
import { auth } from '../../firebase.config'
import { storage } from '../../firebase.config';
import { db } from '../../firebase.config';
const userCredential = await createUserWithEmailAndPassword(auth, email, password)
const user = userCredential.user
const storageRef = ref(storage, `images/${username}`)
const uploadTask = uploadBytesResumable(storageRef, file)
uploadTask.on((error)=>{
toast.error(error.message)
},()=>{
getDownloadURL(uploadTask.snapshot.ref).then(async(downloadURL)=>{
// update user profile
await updateProfile(user, {
displayName: username,
photoURL: downloadURL
})
// store user data in firestore database
await setDoc(doc(db, 'users', user.uid), {
uid: user.uid,
displayName: username,
phone,
email,
sex: userSex,
photoURL: downloadURL
})
})
})
toast.success('Account created')
setLoading(false)
} catch (error) {
setLoading(false)
toast.error('Something went wrong')
}
}

Passing state in email actions -continue URL w react / firebase v11.4.2

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?

createUserWithEmailAndPassword method not adding user to firebase authentication collection

I'm using a signup form that takes in an email and a password to create a new user. I'm not getting an error and popup comes to either save or update the password. However when I look at my firebase console under the authentication tab, I'm not seeing the newly created user. I'm using https://firebase.google.com/docs/auth/web/password-auth as a guide.
import {initializeApp } from 'firebase/app';
import { getAuth, createUserWithEmailAndPassword } from 'firebase/auth';
import {getDatabase, ref, set} from "firebase/database";
//import { getFirestore, collection,doc, getDocs, setDoc } from 'firebase/firestore';
import {
signInWithRedirect,
signInWithEmailAndPassword,
signInWithPopup,
GoogleAuthProvider
} from 'firebase/auth';
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyB8FRK9lJ8WFJa5MnCraDBTiJWN3TJCKmg",
authDomain: "ztm-react-project.firebaseapp.com",
projectId: "ztm-react-project",
storageBucket: "ztm-react-project.appspot.com",
messagingSenderId: "737539305609",
appId: "1:737539305609:web:d7a6bd52d7af973f475658"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const provider = new GoogleAuthProvider();
provider.setCustomParameters({
prompt: "select_account"
});
export const auth = getAuth();
export const signInWithGooglePopup = () => signInWithPopup(auth,provider)
export const createUserDocumentFromAuth = (email, password) => {
console.log('createUserDocFrmAuth');
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
console.log(userCredential.user);
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
console.log(error);
});
}

Getting error when firebase SignOut on react native

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

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

Resources