If I output error
to the console, I get:
{
status: 401,
data: "Invalid password"
}
If I try to output error.data
to the console, I get an error:
The "data" property does not exist in the "FetchBaseQueryError|SerializedError" type. The "data" property does not exist in the "SerializedError" type.ts(2339)
Full code:
const [login, { data, error }] = useLoginMutation()
const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (event) => {
event.preventDefault()
if (credential.user_email.trim() !== '' && credential.user_password.trim() !== '') {
await login(credential)
}
}
useEffect(() => {
if (data !== undefined) {
localStorage.token = data.token
}
}, [data])
useEffect(() => {
if (error !== undefined) {
console.log(error.data)
}
}, [error])
Tell me pls how to do it correctly using typescript.
CodePudding user response:
Use a Type Guard function - more is explained in Type Safe Error Handling
function isFetchBaseQueryError(
error: unknown
): error is FetchBaseQueryError {
return typeof error === 'object' && error != null && 'status' in error
}
useEffect(() => {
if (isFetchBaseQueryError(error)) {
console.log(error.data)
}
}, [error])
Or if you don't need to do this a lot you can also just do
useEffect(() => {
if (error && 'status' in error) {
console.log(error.data)
}
}, [error])