so this is my first project with firebase and im trying to send data to database but the function is not working:
const onSignUp = async (email, password, username) => {
try {
const authUser = await createUserWithEmailAndPassword(
firebase,
email,
password
);
db.collection("users").add({
owner_uid: authUser.user.uid,
usernames: username,
email: authUser.user.email,
profile_pic: await randomProfiles()
})
.then(() => {
console.log("CREATED");
this.props.phase(0);
})
.catch(() => {
console.log("ERROR");
alert("Bruh");
});
} catch (error) {}
};
const randomProfiles = async () => {
const respone = await fetch("https://randomuser.me/api");
const data = await respone.json();
return data.results[0].picture.large;
};
I think the problem might be in
db.collection("users").add({
THIS IS THE EDITED PART NEW CODE:
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
// 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
const firebaseConfig = {
apiKey: "AIzaSyDVy_vUuhZN-qwMmTOUjsViQ4gW36q-Xxk",
authDomain: "social-media-app-d29f2.firebaseapp.com",
projectId: "social-media-app-d29f2",
storageBucket: "social-media-app-d29f2.appspot.com",
messagingSenderId: "103854538000",
appId: "1:103854538000:web:9c77e5a5f7de0c3cb7f995"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
export { auth, db };
so this is my previous way of doing it
CodePudding user response:
You are mixing Firebase SDKs V8 and V9 syntax.
const authUser = await createUserWithEmailAndPassword(...)
is V9 syntax
while
db.collection("users").add(...)
is V8 syntax.
Adapting your code as follows should do the trick. I don't know how you defined the firebase
Object you pass to the createUserWithEmailAndPassword()
method, so I included all the imports and initialization code. It's up to you to adapt this part.
import { initializeApp } from "firebase/app";
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
import { getDatabase, collection, addDoc } from "firebase/firestore";
const app = initializeApp(firebaseConfig);
const onSignUp = async (email, password, username) => {
try {
const auth = getAuth(app);
const authUser = await createUserWithEmailAndPassword(
auth,
email,
password
);
const db = getDatabase(app);
await addDoc(collection(db, "users"), {
owner_uid: authUser.user.uid,
usernames: username,
email: authUser.user.email,
profile_pic: await randomProfiles()
});
this.props.phase(0);
} catch (error) {
console.log(error);
}
};