I want to know that how can we save user data during signup in Firestore.
import {
createUserWithEmailAndPassword,
onAuthStateChanged,
signInWithEmailAndPassword,
signOut,
} from "firebase/auth";
import { collection, setDoc, doc } from "firebase/firestore";
import React, { useContext, useEffect, useState } from "react";
import { auth, db } from "../firebaseConfig";
const AuthContext = React.createContext();
export const useAuth = () => {
return useContext(AuthContext);
};
export const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState();
const [loading, setLoading] = useState(true);
const signup = async (email, password) => {
return createUserWithEmailAndPassword(auth, email, password).then(
(cred) => {
setDoc(doc(collection(db, "users", cred.user.uid)), {
name: "manan",
city: "chd",
});
}
);
};
const login = (email, password) => {
return signInWithEmailAndPassword(auth, email, password);
};
const logout = () => {
return signOut(auth);
};
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
setCurrentUser(user);
setLoading(false);
});
return unsubscribe;
}, []);
const value = {
currentUser,
login,
signup,
logout,
};
return (
<AuthContext.Provider value={value}>
{!loading && children}
</AuthContext.Provider>
);
};
as you can see I have created an AuthContext.js
for all the functions. now, when in signup()
I am not able to store the user data corresponding to their UID... as I have used
setDoc(doc(collection(db, "users", cred.user.uid)), {
name: "manan",
city: "chd",
});
but it is not working at all it's throwing an error
error:
Objects are not valid as a React child (found: object with keys {error}). If you meant to render a collection of children, use an array instead.
CodePudding user response:
you are using both a document and a collection as a reference. you should only use a document reference on a setDoc
from:
setDoc(doc(collection(db, "users", cred.user.uid)), {
name: "manan",
city: "chd",
});
change to:
setDoc(doc(db, "users", cred.user.uid), {
name: "manan",
city: "chd",
});