在 Firebase 中更新个人资料图片

Updating profile picture in firebase

我不确定我在这里做错了什么,我上传了一张新图片到 firebase 存储,然后我用 getDownloadUrl 检索它,然后我更新了用户个人资料 photoURL,但由于某种原因它不起作用.

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是上传的img

不太可能在 updateProfile then 语句运行时更新当前用户。

改为像使用 imgUrl[0] 一样更新 useState 挂钩。

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

如果您想验证个人资料图像是否已更新打印值:

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