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

121 views Asked by At

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("");
  };
1

There are 1 answers

2
Frank van Puffelen On BEST ANSWER

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