Home > database >  how to add current user uid to user collection when user signup in cloud firestore?
how to add current user uid to user collection when user signup in cloud firestore?

Time:12-24

I want to add user id (which is unique generated by firestore) in userID field of users collection.

so for this i created this handle function

const handleSubmit = async (e) => {
    e.preventDefault();
    const { email, password, fullname, username } = credentials
    try {
        await createUser({ email, password, fullname, username })
    } catch (error) {
        console.log(error)
        setError(error.message)
    }

}

and this handle function calling createUser function from Authcontext

export const AuthContextProvider = ({ children }) => {
const [user, setUser] = useState('')
const [refUser, setRefUser] = useState('')

console.log('checking on top ', user)
// Sign Up function 
const createUser = async ({ email, password, fullname, username }) => {
    await createUserWithEmailAndPassword(auth, email, password)

    // creatinguser collection
    const date = new Date().toISOString();
    const userRef = await addDoc(collection(db, "users"), {
        userId: '',
        username: username,
        email: email,
        name: fullname,
        followers: [],
        followings: [],
        posts: [],
        date: date
    });
    
    await updateDoc(doc(db, "users", `${userRef?.id}`), {
        userId: "user?.uid"
    });
}

useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (currentUser) => {
        setUser(currentUser);
    return () => {
        unsubscribe();
    };
});

return (
    <AuthContext.Provider value={{ createUser, user, refUser }}>
        {children}
    </AuthContext.Provider>
)

}

so please let me know how to updateDoc only that time when user create new account/ signup so that i can store there uid in userID field.

CodePudding user response:

The createUserWithEmailAndPassword() function returns an instance of UserCredential. You can read UID of new user as shown below:

const createUser = async ({ email, password, fullname, username }) => {
  const { user } = await createUserWithEmailAndPassword(auth, email, password)
  const userId = user.uid; 
 
  // Add document in user collection
  const userRef = await setDoc(doc(db, "users", userId), {
    email,
    userId,
    username,
    name: fullname,
    followers: [],
    followings: [],
    posts: [],
    date: new Date().toISOString() // <-- or new Date(); for Timestamp field
  }); 
}

You can use the userId as the document ID as it makes it easier to get user's document later using getDoc() instead of running a query to find a document.

  • Related