Getting error with RTK query:
Type 'FetchBaseQueryError | SerializedError' is not assignable to type 'ReactNode'.
const { data, error, isLoading } = useGetDataQuery();
return (
<div>{error}</div>
);
How to solve it? What should I display instead?
Quoting the docs on Type Safe Error Handling:
Type safe error handling
A. When an error is gracefully provided from a base query, RTK query will provide the error directly.
B. If an unexpected error is thrown by user code rather than a handled error, that error will be transformed into a SerializedError shape.
Users should make sure that they are checking which kind of error they are dealing with before attempting to access its properties. This can be done in a type safe manner either by using a type guard, e.g. by checking for discriminated properties, or using a type predicate.
When using fetchBaseQuery, as your base query, errors will be of type FetchBaseQueryError | SerializedError.
When using fetchBaseQuery, the error property returned from a hook will have the type FetchBaseQueryError | SerializedError | undefined. If an error is present, you can access error properties after narrowing the type to either FetchBaseQueryError or SerializedError.
Example:
import { api } from './services/api'
function PostDetail() {
const { data, error, isLoading } = usePostsQuery()
if (isLoading) {
return <div>Loading...</div>
}
// Possible values of error:
// FetchBaseQueryError | SerializedError | undefined
// 1) Checking if error is NOT undefined:
if (error) {
// 2) Checking if error is FetchBaseQueryError based on
// discriminated property 'status':
if ('status' in error) {
// you can access all properties of `FetchBaseQueryError` here
const errMsg = 'error' in error ? error.error : JSON.stringify(error.data)
return (
<div>
<div>An error has occurred:</div>
<div>{errMsg}</div>
</div>
)
// 3) We're left with the 3rd case, SerializedError:
} else {
// you can access all properties of `SerializedError` here
return <div>{error.message}</div>
}
}
simple answer
'message' in error ? error.message : ''
or if you want the error property instead of message
'error' in error ? error.error : ''
Check out the in operator's documentation. It allows you narrow down a type. In this case you want to know if its 'FetchBaseQueryError | SerializedError' since message or error only exist on one of them it will narrow it down to the correct type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With