skip to Main Content

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:

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    Problem

    if ('data' in error) {}
    

    Basically, the upper approach will work fine for this type of response error:

    // the upper approach will work fine for this.
    error: {
      data: "Error message here."
    }
    

    But when you have an error response like the below one. You might have faced another warning Property 'error' does not exist on type '{}'.

    // the approach is not working for this.
    error: {
      data: {
        error: "Error message here."
      }
    }
    

    Solution:

    First, you can add an error state using useState and then set the type of the state. The type can be any or you can write a custom type 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:

    const [error, setError] = useState<any>(undefined);
    const [login, { isLoading, error: resError }] = useLoginMutation();
    
    useEffect(() => {
      if (resError && 'data' in resError) {
        setError(resError.data);
      }
    }, [resError]);
    
    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>
    )
    

  2. As you see, there two different types:

    1. FetchBaseQueryError
    2. SerializedError

    These 2 have different return types. SerializedError return type is:

    export interface SerializedError {
      name?: string
      message?: string
      stack?: string
      code?: string
    }
    

    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:

    if ('data' in error) {}
    

    You can read more here:

    RTK-Query Error Handling

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search