首页 > 解决方案 > 如何使用 Firebase signInWithCredentials() 设置用户的显示名称和电子邮件

问题描述

我正在为我的React Native应用程序编写登录/注册页面,并且正在使用 Firebase 的signInWithCredential()功能。

正如您在下面的代码中看到的,我传递了一个凭据,如果响应显示它是一个新用户,我将附加到我的数据库,否则我将它们发送到主屏幕。

await firebase
    .auth()
    .signInWithCredential(credential)
    .then((response) => {
        if (response.additionalUserInfo.isNewUser) {
            setShowVerifier(false);
            setShowRegistration(true);

            // append data to database if user is new
            const data = { firstName, lastName, email, phoneNumber };
            db.collection("users")
                .doc(response.user.uid)
                .set(data)
                .then(() => {
                    setShowPhoneNumber(true);
                    setShowVerifier(false);
                    setShowRegistration(false);

                    navigation.navigate("Home");
                }).catch(() => {
                    alert("Error creating account, try again");
                });
        } else {
           setShowVerifier(false);
           setShowPhoneNumber(true);

           // set verification code to empty string
           setVerificationCode("");

           navigation.navigate("Home");
        }
    });

当我发现用户实际上是新用户时,我将如何更新该用户的 Firebase 身份验证信息,例如他们的 displayName 和电子邮件?(如下 JSON 响应所示)

"user": Object {
    "displayName": null,
    "email": null,
    "emailVerified": false,
    "isAnonymous": false,
    "lastLoginAt": "1603914278694",
    "photoURL": null,
}

标签: javascriptfirebasereact-nativefirebase-authentication

解决方案


将此代码块添加到上面找到的代码块中。

auth.currentUser.updateProfile({
    displayName: firstName + " " + lastName,
    email: email,
});

更新的代码块:

await firebase
    .auth()
    .signInWithCredential(credential)
    .then((response) => {
        if (response.additionalUserInfo.isNewUser) {
            setShowVerifier(false);
            setShowRegistration(true);

            // append data to database if user is new
            const data = { firstName, lastName, email, phoneNumber };
            db.collection("users")
                .doc(response.user.uid)
                .set(data)
                .then(() => {
                    setShowPhoneNumber(true);
                    setShowVerifier(false);
                    setShowRegistration(false);

                    navigation.navigate("Home");
                }).catch(() => {
                    alert("Error creating account, try again");
                });
        } else {
           setShowVerifier(false);
           setShowPhoneNumber(true);

           // set verification code to empty string
           setVerificationCode("");

           navigation.navigate("Home");
        }
    });

推荐阅读