繁体   English   中英

Firebase 使用 typescript 的 auth.currentUser 错误

[英]Firebase auth.currentUser error using typescript

使用 firebase 配置Argument of type 'User | null' is not assignable to parameter of type 'User'. Type 'null' is not assignable to type 'User'.时,出现以下错误: Argument of type 'User | null' is not assignable to parameter of type 'User'. Type 'null' is not assignable to type 'User'.

错误在这里:auth.currentUser我不清楚它是什么类型。

updateProfile(auth.currentUser, {
                    displayName: name
                }

完整代码:

import { getAuth, createUserWithEmailAndPassword, signOut, onAuthStateChanged, signInWithEmailAndPassword, updateProfile } from "firebase/auth";
import { useEffect, useState } from "react";
import FirebaseInitialization from "../Firebase/Firebase.init";



FirebaseInitialization()

interface IUseFirebaseProps {
}

const UseFirebase: React.FunctionComponent<IUseFirebaseProps> = (props) => {
    const [user, setUser] = useState({})
    const [error, setError] = useState('')
    const [admin, setAdmin] = useState(false)
    const [isLoading, setIsLoading] = useState(true)
    const auth = getAuth()


      // REGISTER WITH EMAIL AND PASSWORD
      const RegisterUser = (email: string, password:string, name:string, history: any) => {
        setIsLoading(true)
        createUserWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                const newUser = { email, displayName: name };
                setUser(newUser);
                setError('')
                updateProfile(auth.currentUser, {
                    displayName: name
                }).then(() => {
                }).catch((error) => {
                });
                history.replace('/');
            })
            .catch((error) => {

                const errorMessage = error.message;
                setError(errorMessage)
            }).finally(() => setIsLoading(false));
    }
  return <h2>Firebase</h2>
};

export default UseFirebase;

我该如何解决这个问题? 谁能帮我?

auth.currentUser的值可以是null 在这种情况下,您可以直接从UserCredential object 传递User object。尝试重构代码,如下所示:

const RegisterUser = async (email: string, password: string, name: string, history: any) => {
  setIsLoading(true)
  const userCredential = await createUserWithEmailAndPassword(auth, email, password)
  
  const newUser = {
    email,
    displayName: name
  };
  
  setUser(newUser);
  setError('')
  
  // Pass userCredential.user instead of auth.currentUser
  updateProfile(userCredential.user, {
    displayName: name
  }).then(() => {}).catch((error) => {});
    history.replace('/');
  })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM