Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'
. When I try using optional chaining, a different error pops up saying
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 occurs when trying to destructure the object
RegisterUser(newUser?.email, newUser?.password, newUser?.name, navigate)
This is 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 point out what kind of mistake I might have made?