【问题标题】:ReactJS firebase auth displayName return nullReactJS firebase auth displayName 返回 null
【发布时间】:2022-01-16 02:39:03
【问题描述】:

我正在开发一个 ReactJS 应用程序,并集成了 Firebase 的身份验证来创建用户和登录功能。我无法弄清楚如何设置 displayName,因为我创建的每个帐户的 displayName 都为“null”。这是我创建用户帐户的功能。我浏览了 Firebase 文档,只能找到获取 displayName 而不是如何设置它?

function CreateUser({ setUserInformation, setErrors, setLoggedIn }) {
  const signUpUser = useCallback(
    (e) => {
      e.preventDefault();

      const email = e.currentTarget.email.value;
      const password = e.currentTarget.password.value;
      const displayName = e.currentTarget.displayName.value;
      // const displayName = document.getElementById("name").value;
      const auth = getAuth();

      createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
          // Signed in
          const user = userCredential.user;
          setLoggedIn(true);
          setUserInformation({
            email: user.email,
            displayName: user.displayName,
            uid: user.uid,
            accessToken: user.accessToken,
          });
          setErrors();
        })
        .catch((error) => {
          const errorCode = error.code;
          const errorMessage = error.message;
          console.warn({ error, errorCode, errorMessage });
          setErrors(errorMessage);
        });
    },
    [setErrors, setLoggedIn, setUserInformation]
  );

我的 App.js:

function App() {
  // Track if user is logged in
  const [loggedIn, setLoggedIn] = useState(false);
  // check to see if there is any loading...
  const [loading, setLoading] = useState(true);
  //store user information in state
  const [userInformation, setUserInformation] = useState({});
  const [appInitialized, setAppInitialized] = useState(false);
  // Error
  const [errors, setErrors] = useState();

  // Ensure app is initialized when it is ready to be
  useEffect(() => {
    // initialized firebase
    initializeApp(FirebaseConfig);
    setAppInitialized(true);
  }, []);

  // check to see if user is logged in
  // user loads page, check their status
  // set state accordingly
  useEffect(() => {
    if (appInitialized) {
      const auth = getAuth();
      onAuthStateChanged(auth, (user) => {
        if (user) {
          //user is signed in
          setUserInformation(user);
          setLoggedIn(true);
        } else {
          // user is signed out
          setUserInformation({});
          setLoggedIn(false);
        }
        // whenever state cxhanges setLoading to false
        setLoading(false);
      });
    }
  }, [appInitialized]);

  function logout() {
    const auth = getAuth();
    signOut(auth)
      .then(() => {
        setUserInformation({});
        setLoggedIn(false);
        setErrors();
      })
      .catch((error) => {
        console.warn(error);
        setErrors(error);
      });
  }

  if (loading || !appInitialized) return null;

  return (
    <div>
      <Header
        logout={logout}
        loggedIn={loggedIn}
        userInformation={userInformation}
      />
      <Router>
        <Routes>
          <Route
            path="/login"
            element={
              !loggedIn ? (
                <Login
                  setErrors={setErrors}
                  setLoggedIn={setLoggedIn}
                  setUserInformation={setUserInformation}
                />
              ) : (
                <Navigate to="/" />
              )
            }
          />
          <Route
            path="/create-user"
            element={
              !loggedIn ? (
                <CreateUser
                  setLoggedIn={setLoggedIn}
                  setUserInformation={setUserInformation}
                  setErrors={setErrors}
                />
              ) : (
                <Navigate to="/" />
              )
            }
          />
        </Router>

【问题讨论】:

  • 你能分享你的setUserInformation()函数的代码吗?我想确认您是否在其中的任何地方使用updateProfile
  • @Dharmaraj 我更新了我的代码,我的 setUserInformation() 在 App.js 中并传递到我的 CreateUserPage.js 上的 CreateUser 函数

标签: javascript reactjs firebase firebase-authentication


【解决方案1】:

当新用户注册时,您必须使用updateProfile() 方法更新他们的显示名称,如下所示:

const displayName = e.currentTarget.displayName.value;

createUserWithEmailAndPassword(auth, email, password)
  .then(async (userCredential) => {
    //  ^^^^^ async function 
    // Signed in
    const user = userCredential.user;
    setLoggedIn(true);

    // Updating user name
    await updateProfile(auth.currentUser, { displayName })

    setUserInformation({
      displayName,
      email: user.email,
      uid: user.uid,
      accessToken: user.accessToken,
    });
    setErrors();
  })

现在应该更新user.displayName。 查看documentation 了解更多信息。

【讨论】:

  • 天哪,非常感谢它的工作!!
猜你喜欢
  • 1970-01-01
  • 2016-10-06
  • 2019-04-12
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 2019-08-05
相关资源
最近更新 更多