firestore not creating document with setDoc - reactjs

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

Related

Firebase Error -> storageRef.putString() is not a function. Trying to upload an image from a post to firebase storage

I am trying to take a post that contains an image and upload it to firebase storage. Originally I had an error saying storage was not a function, but have change it to a new const as storageRef.
Now I am getting an error that .putString() isn't a function. I am passing in an image from my state variable and "data_url" as the 2nd arg. Why am I getting this error and is there anything else that seems to be off with my code?
Firebase.js
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
import { getStorage, ref } from 'firebase/storage';
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const storage = getStorage();
File where Error is happening:
import React, { useRef, useState } from 'react';
import Image from 'next/image';
import { useSession } from 'next-auth/react';
import { db, storage } from '../firebase';
import { collection, serverTimestamp, addDoc } from 'firebase/firestore';
import { ref } from 'firebase/storage';
function InputBox() {
const { data: session } = useSession();
const [imageToPost, setImageToPost] = useState(null);
const inputRef = useRef(null);
const filePickerRef = useRef(null);
const sendPost = (e) => {
e.preventDefault();
if (!inputRef.current.value) return;
try {
const docRef = addDoc(collection(db, 'posts'), {
message: inputRef.current.value,
name: session.user.name,
email: session.user.email,
image: session.user.email,
timestamp: serverTimestamp(),
}).then((doc) => {
if (imageToPost) {
const storageRef = ref(storage, `posts/${doc.id}`);
const uploadTask = storageRef.putString(imageToPost, 'data_url');
removeImage();
uploadTask.on(
'state_change',
null,
(error) => console.error(error),
() => {
// When upload completes
storageRef
.ref(`posts`)
.child(doc.id)
.getDownloadURL()
.then((url) => {
docRef.addDoc(
Collection(db, 'posts')
.doc(doc.id)
.set(
{
postImage: url,
},
{ merge: true }
)
);
});
}
);
}
});
console.log(docRef.id);
} catch (e) {
console.log('ERROR ADDING DOC:', e);
}
Thanks in advance, Firebase is updating all the time and I still find this somewhat confusing.

Why is db.collection not working for firebase. I am using next.js w/ useSession() from next-auth

All the answers on stack are a bit old and as firebase is constantly updating their docs I am having a lot of trouble w/ firebase. Could someone please shed some light on this for me?
I am using next.js and I have next-auth linked with Facebook. I want to take the current user session information and give it to firebase
Here I have my firebase.js file:
import firebase from 'firebase/compat/app';
import 'firebase/compat/storage';
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore/lite';
import { getStorage } from 'firebase/storage';
const firebaseConfig = {
apiKey: 'SECRET',
authDomain: 'SECRET',
projectId: 'SECRET',
storageBucket: 'SECRET',
messagingSenderId: 'SECRET',
appId: 'SECRET',
};
const app = !firebase.apps.length
? firebase.initializeApp(firebaseConfig)
: firebase.app();
// const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const storage = getStorage(app);
export { db, storage };
And then below is the code the error is being issued from. I have tired a few solutions by trying to use doc, getDoc but it doesn't match up with my "session.user.name" and such.
Here is my .js file that is trying to use firebase. the issue states is coming from db.collection(). I am using useSession() with next.js ti get my server-side data
import React, { useRef, useEffect } from 'react';
import Image from 'next/image';
import { useSession } from 'next-auth/react';
import { EmojiHappyIcon } from '#heroicons/react/outline';
import { CameraIcon, VideoCameraIcon } from '#heroicons/react/solid';
import { db } from '../firebase';
import firebase from 'firebase/app';
import { collection } from 'firebase/firestore';
function InputBox() {
const { data: session } = useSession();
const inputRef = useRef(null);
const sendPost = (e) => {
e.preventDefault();
if (!inputRef.current.value) return;
db.collection('posts').add({
message: inputRef.current.value,
name: session.user.name,
email: session.user.email,
image: session.user.image,
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
});
inputRef.current.value = '';
};
[SOLVED]
Due to new docs the v9> firebase has changed the serverTimestamp() function.
import { useSession } from 'next-auth/react';
import { EmojiHappyIcon } from '#heroicons/react/outline';
import { CameraIcon, VideoCameraIcon } from '#heroicons/react/solid';
import { db } from '../firebase';
import { collection, serverTimestamp, addDoc } from 'firebase/firestore';
function InputBox() {
const { data: session } = useSession();
const inputRef = useRef(null);
const sendPost = (e) => {
e.preventDefault();
if (!inputRef.current.value) return;
try {
const docRef = addDoc(collection(db, 'posts'), {
message: inputRef.current.value,
name: session.user.name,
email: session.user.email,
image: session.user.email,
timestamp: serverTimestamp(),
});
console.log(docRef.id);
} catch (e) {
console.log('ERROR ADDING DOC:', e);
}
inputRef.current.value = '';
};
I threw in a try/catch to handle the issue.
timestamp: firebase.firestore.FieldValue.serverTimestamp() -> timestamp: serverTimestamp()
also need to import {serverTimestamp} from 'firebase/firestore'

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

signInWithPopup method not working firebase react.js

I am try to authenticate with google signin in firebase with react and redux. But the problem is when the popup window opens then it shows not able to reach page. I am using firebase v9.
Here is my firebase config file
import { initializeApp } from "firebase/app";
import {
getAuth,
GoogleAuthProvider,
FacebookAuthProvider,
createUserWithEmailAndPassword,
updateProfile,
signInWithEmailAndPassword,
signOut,
onAuthStateChanged,
signInWithPopup,
signInWithRedirect
} from "firebase/auth";
const config = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
};
initializeApp(config);
const auth = getAuth();
const googleAuthProvider = new GoogleAuthProvider();
const facebookAuthProvider = new FacebookAuthProvider();
export {
auth,
googleAuthProvider,
facebookAuthProvider,
createUserWithEmailAndPassword,
updateProfile,
signInWithEmailAndPassword,
signOut,
onAuthStateChanged,
signInWithPopup,
signInWithRedirect
};
Here below is the google signin trigger reducer
export const googleSignInitiate = () => {
return (dispatch) => {
dispatch(googleSignInStart());
signInWithPopup(auth, googleAuthProvider)
.then(({ user }) => {
dispatch(googleSignInSuccess(user));
})
.catch((error) => {
dispatch(googleSignInFail(error.message));
});
};
};
Here below is the error popup window
Can anyone tell me how to fix this.

React Native authentication and cloud Firestore for web apps

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

Resources