Home > Software engineering >  Updating profile picture in firebase
Updating profile picture in firebase

Time:05-11

i'm not sure what i'm doing wrong here, i upload a new picture to firebase storage, then i retrieve it with getDownloadUrl, and then i update the user profile photoURL, but for some reason it's not working.

const imgPath = ref(storage, "images/");
  const imgUpload = () => {
    if (uImg == null) return;

    const imgRef = ref(storage, `images/${uImg.name   v4()}`);
    uploadBytes(imgRef, uImg).then(() => {
      listAll(imgPath).then((response) => {
        response.items.forEach((item) => {
          getDownloadURL(item).then((url) => {
            setImgUrl([url]);

            updateProfile(auth.currentUser, {
              photoURL: `${imgUrl[0]}`,
            })
              .then(() => {
                setProfileImg(auth.currentUser.photoURL);
                console.log("success");
              })
              .catch((error) => {
                console.log(error);
              });
          });
        });
      });
    });
  };

uImg is the uploaded img

CodePudding user response:

It is unlikely the current user is updated by the time the updateProfile then statement runs.

Instead update the useState hook as with the imgUrl[0].

updateProfile(auth.currentUser, { photoURL: `${imgUrl[0]}` })
     .then(() => {
        setProfileImg(imgUrl[0]);
        console.log("success");
 }).catch((error) => { console.log(error); });

If you want to verify that the profile image was updated print of the value:

const auth = getAuth();
useEffect(() => {
  console.log("Profile:", auth.currentUser?.photoURL);
}, []);
  • Related