Home > Software design >  How can I Update Document in Collection firebase
How can I Update Document in Collection firebase

Time:10-05

So I have this Avatar and I want to display the Avatar not only on the Profile but also on the Feed and some other pages. In my "User" collection, I have an object called "photoURL". What I’m trying to do is that when someone is adding or changing the Profile picture, the "photoURL" should update automatically in the collection.

My logic behind this is that I need this to display the photo on other pages and to do that I have to save it to the collection so I can access it. Maybe my logic is wrong, I don't know, but I didn't find another way and I think this is the easiest.

This is the user collection code:

 function onSignUp() {
    firebase
      .auth()
      .createUserWithEmailAndPassword(email, password)
      .then((result) => {
        firebase
          .firestore()
          .collection("users")
          .doc(firebase.auth().currentUser.uid)
          .set({
            name,
            email,
            role: isTeacher ? "pädagoge" : "parent",
            photoURL: null,
          });
        console.log(result);
      })
      .catch((error) => {
        console.log(error);
      });

The Avatar Chooser Code :

async function handleFileInputChange(e) {
    const files = e.target.files;
    const file = files[0];

    const storage = firebase.storage();
    const usersImageRef = storage
      .ref()
      .child(`users/${user.uid}/profilepicture.jpg`);

    const snap = await usersImageRef.put(file);

    const donwloadURL = await snap.ref.getDownloadURL();
    setDownloadURL(donwloadURL);

    // Save photoUrl in user collection
    // -> {name : "...", email : "...", role : "...", photoUrl : "..."}
    
    await firebase.auth().currentUser.updateProfile({ photoURL: donwloadURL });
    setProfilePictureUrl(donwloadURL);
  }

I saw this example on firbase doc:

db.collection("users").doc("frank").update({
  favorites: {
    food: "Ice Cream"
  }
}).then(function() {
  console.log("Frank food updated");
});

But I would need the code to do it dynamically, and I'm not sure how.

CodePudding user response:

you can add a .then() to your handleFileInputChange() function like this:

await firebase.auth().currentUser.updateProfile({ photoURL: downloadURL }).then(()=>{
    db.collection("users").doc("frank").update({
        userProfileImage: downloadURL
  }).catch((err)=>{
      //handle errors
  });
}).catch((err)=>{
      //handle errors
 }); 

do take note of spelling of downloadURL too.

CodePudding user response:

 firebase
          .firestore()
          .collection("users")
          .doc(firebase.auth().currentUser.uid)
          .update({
            name:name,
            email:email,
            role: isTeacher ? "pädagoge" : "parent",
            photoURL: photourl,
          });
  • Related