When I try to destructure my state object in react typescript, I get an Object is possibly 'undefined'
error. If I use optional chaining I got this error const newUser: NewUser | undefined Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.
The error is showing when I am trying to destructure object RegisterUser(newUser?.email, newUser?.password, newUser?.name, navigate)
My Code:
type NewUser ={
name: string,
email: string,
password: string,
navigate: string
}
const Register = () => {
const [newUser, setNewUser] = useState<NewUser>() // single object will return
const [RegisterUser] = UseFirebase()
const navigate = useNavigate()
const handleValues = (e: any) => {
const field = e.target.name;
const value = e.target.value
const user: any = { ...newUser }
user[field] = value
setNewUser(user)
}
const handleRegister = (e: any) => {
e.preventDefault()
// ERROR
RegisterUser(newUser.email, newUser.password, newUser.name, navigate)
// console.log('user name', newUser.name, newUser.email, newUser.password);
}
.......
Could someone please tell me what type of mistake I made?
CodePudding user response:
Well that the typescript for yaa, you need to check first that you will not get undefined as a value by simply doing condition check like this
const handleRegister = (e: any) => {
e.preventDefault()
if (newUser?.email && newUser?.password && newUser?.name) {
RegisterUser(newUser.email, newUser.password, newUser.name, navigate)
} else {
// show some error handling here or error to user that he didnt enter value etc
}
}
CodePudding user response:
If your object is not undefined, you should try
RegisterUser(newUser!.email, newUser!.password, newUser!.name, navigate)