When configuring typescript with firebase, I am getting the following error: Argument of type 'User | null' is not assignable to parameter of type 'User'. Type 'null' is not assignable to type 'User'.
The error is here: auth.currentUser It is unclear to me what type it would be.
updateProfile(auth.currentUser, {
displayName: name
}
Full code:
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;
How can I solve this? can anyone help me?
CodePudding user response:
The value of auth.currentUser
can be null
. In this case you can pass User
object directly from UserCredential
object. Try refactoring the code as shown below:
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('/');
})
}