【发布时间】:2022-11-29 09:23:46
【问题描述】:
我目前正在尝试使用 Firebase 身份验证和 React 创建一个用户身份验证系统。我希望我的用户在注册时能够提供他们的用户名(又名displayName)。这是它的当前代码:
带有 firebase 初始化的脚本,firebase.js:
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = { /* Config information goes here */ };
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
包含与注册和更新配置文件相关的身份验证上下文和功能的脚本,AuthContext.jsx:
import { auth } from "../firebase";
import { useState, useEffect, useContext, createContext } from "react";
import {
createUserWithEmailAndPassword,
onAuthStateChanged,
updateProfile
} from "firebase/auth";
const AuthContext = createContext();
export function useAuth() {
return useContext(AuthContext);
}
export function AuthProvider({children}) {
const [currentUser, setCurrentUser] = useState();
const [isLoading, setIsLoading] = useState(true);
function signup(email, password) {
return createUserWithEmailAndPassword(auth, email, password);
}
function updateInformation(name) {
return updateProfile(currentUser, {displayName: name});
}
useEffect(() => {
const unsubscriber = onAuthStateChanged(auth, (user) => {
setIsLoading(true);
setCurrentUser(user);
setIsLoading(false);
});
return unsubscriber;
}, []);
const value = {
currentUser,
signup,
updateInformation
}
return (
<AuthContext.Provider value={value}>
{!isLoading && children}
</AuthContext.Provider>
);
}
包含注册页面的脚本,Signup.jsx:
import { useState } from "react";
import { useAuth } from "../contexts/AuthContext";
function Signup() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [username, setUsername] = useState("");
const {signup, updateInformation} = useAuth();
async function handleSubmit(e) {
e.preventDefault();
try {
await signup(email, password);
await updateInformation(username); // Error happens here
} catch (error) {
console.log(error.message);
}
}
return (
<div>
<h1>Create an account</h1>
<form onSubmit={handleSubmit}>
<input type="text" value={username} onChange={(e) => setUsername(e.target.value)} placeholder="Username"/>
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email"/>
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password"/>
<input type="submit" value="Sign up"/>
</form>
</div>
);
}
export default Signup;
这段代码背后的想法是,首先将调用createUserWithEmailAndPassword函数,注册用户并自动登录。这将触发onAuthStateChanged中的回调函数,更新currentUser状态。然后将调用updateProfile函数,更改currentUser持有的账户的displayName。至少,这是我认为会发生的事情。但是,当代码运行时,updateProfile 会抛出错误,指出 currentUser 为空。为什么会这样?
【问题讨论】:
-
你能分享你使用
getIdToken()的代码吗? -
我没有在我的代码中的任何地方使用
getIdToken()。我猜它是由updateProfile调用的? -
@Dharmaraj 我刚刚编辑了问题。希望这个问题现在更容易理解 :)
标签: javascript reactjs firebase firebase-authentication