如何在Firebase中更新用户配置文件?

inn6fuwd  于 2023-10-22  发布在  其他
关注(0)|答案(2)|浏览(145)

我试图更新用户配置文件,我读this documentation。但是,为什么我不能改变我的displayName?它总是给予我null.
它还给予了TypeError: userNow is null
我应该按照哪一个更新/编辑用户配置文件?

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Update User Profile</title>
        <script src="https://www.gstatic.com/firebasejs/4.11.0/firebase.js"></script>
        <script src="core.js">
        </script>
    </head>
    <body>
        <script>
            var authRef = firebase.auth();
            authRef.onAuthStateChanged(function(user) {
                if (user) {
                    console.log('Display name onAuthStateChanged : '+user.displayName);
                } else {
                    console.log('not login');
                }
            });
            
            
            var userNow = firebase.auth().currentUser;
            userNow.updateProfile({
                displayName: "Jane Q. User",
                photoURL: "https://example.com/jane-q-user/profile.jpg"
            }).then(function() {
                var displayName = userNow.displayName;
                var photoURL = userNow.photoURL;
            }, function(error) {
                
            });

        </script>
        <script src="js/jquery-3.3.1.min.js"></script>
    </body>
</html>
uklbhaso

uklbhaso1#

将您的代码从var userNow = firebase.auth().currentUser;开始 Package 在一个函数中。正如@Andre Kool所说,你需要确保你首先登录(因为它是一个匿名操作,然后尝试将用户数据更新为:

var authRef = firebase.auth();
    authRef.onAuthStateChanged(function(user) {
        if (user) {
            console.log('Display name onAuthStateChanged : '+user.displayName);
            _updateUserData();
        } else {
            console.log('not login');
        }
    });
          
    function _updateUserData(){
      var userNow = firebase.auth().currentUser;
        userNow.updateProfile({
        displayName: "Jane Q. User",
        photoURL: "https://example.com/jane-q-user/profile.jpg"
      }).then(function() {
        var displayName = userNow.displayName;
        var photoURL = userNow.photoURL;
      }, function(error) {
        console.log(error)
      });
  }
bkhjykvo

bkhjykvo2#

使用useState获取值

<input
      className="h-[30px] rounded-2xl p-5"
      placeholder="new name"
      onChange={(e) => setUpdateName(e.target.value)}
      type="text"
  />

 const [updateprofileUrl, setUpdateProfileUrl] = useState();
  const [updatename, setUpdateName] = useState();
  const updateProfileitems = async () => {
    try {
        await updateProfile(auth.currentUser, {
        displayName: updatename,
        photoURL: updateprofileUrl,
      });
       console.log("Profile Update");
    } catch (error) {
      console.log(error);
    }
  };

相关问题