Search code examples
javascriptreactjsfirebasegoogle-cloud-firestorereactjs.net

Add a new collection in firebase when the user create account using uid of user in react js


I make to to do list website but I want to create for each new user who register a new collection. when it created must also create automatically a new doucment in firebase for it and then write the data(to do list) in this docu. (I am using firebase cloud)

here a new structure which i wish:

const handleSignUp = (e) => { // singup function in Component Signup.jsx 
e.preventDefault();
createUserWithEmailAndPassword(auth, email, password)
  .then(() => {
    // Signed up
    navigate("/");
  })
  .catch((error) => {
    alert.message("error");
    // ..
  }); };


 // create todo in Main.jsx
  const createTodo = async (e) => {
    e.preventDefault(e); // no reload for the page
    if (input === "") {
      alert("pleas enter a valid statment");
      return;
    } else {
      const docRef = await addDoc(collection(db, "todo"), {
        text: input,
        completed: false,
      });
      console.log("Document written with ID: ", docRef.id);
    }
    setInput("");
  };

Solution

  • The structure you needs for this is:

    Users (collection)
      $uid (documents)
        Todos (collection)
          $todoId (documents)
    

    After the user is signed in, you can then add a Todo to their collection with:

    const uid = auth.currentUser.uid;
    const todos = collection(db, "Users", uid, "Todos");
    const docRef = await addDoc(todos, {
      text: input,
      completed: false,
    });