I’m using React Ts, and Rtk query. I’m trying to show the API response error on the UI. It’s working but giving me a warning. It’s telling me to set the error type for the response errors. How can I add an error type for response errors? Or are there any other solutions? This is how I’m showing the error.
const [login, { isLoading, isError, error }] = useLoginMutation();
return (
<div>
{isError && (
<div className="bg-neRed-200 text-neRed-900 font-medium py-1 px-2 text-sm rounded">
{error?.data?.error}
</div>
)}
</div>
)
Basically, it’s giving me this error:
Property 'data' does not exist on type 'FetchBaseQueryError | SerializedError'.
Property 'data' does not exist on type 'SerializedError'.
And this is how it’s looking on the code editor:
2
Answers
Problem
Basically, the upper approach will work fine for this type of response error:
But when you have an error response like the below one. You might have faced another warning
Property 'error' does not exist on type '{}'.
Solution:
First, you can add an error state using
useState
and then set thetype
of the state. Thetype
can beany
or you can write a customtype
as well. Just make the type optional. Then you can save the inner object in the state. Then you can simply show the error to your UI. Here is an example:As you see, there two different types:
FetchBaseQueryError
SerializedError
These 2 have different return types.
SerializedError
return type is:As you can see, there is no
data
property within.So if you want to get only
FetchBaseQueryError
errors, you can check as this to be ensured:You can read more here:
RTK-Query Error Handling