Accessing error object in response from API Slice redux toolit

22 views Asked by At

I have this slice

 ...
    baseQuery: fetchBaseQuery({
        baseUrl: BASE_ENDPOINT,
        prepareHeaders: headers => {
            const token = Cookies.get(TOKEN_COOKIE)
            if (token) headers.set('authorization', `Bearer ${token}`);
            return headers;
        },
    }),
    getUserData: builder.query<SomeProps, void>({
        query: () => ({
            url: "...",
            headers: {
                'Content-Type': 'application/json',
            }
        }),
...

At one point in this

const {
    data,
    isLoading,
    error
} = useGetUserInfoQuery()

error becomes true and contains this

{"status":500,"data":{"status":"FAILED","message":"Some message I want to display."}}

However, the TypeScript compiler complains about this

error.data.message

It says

Property  data  does not exist on type  FetchBaseQueryError | SerializedError  Property  data  does not exist on type  SerializedError 

I cannot even do this

error!!.data!!.message!!

How would I access data.message in error?

1

There are 1 answers

0
Drew Reese On

The error type is unknown, so you'll need to cast it to an appropriate type if you would like to access specific properties.

See useQuery hook declarations:

type UseQuery = (
  arg: any | SkipToken,
  options?: UseQueryOptions,
) => UseQueryResult

type UseQueryResult<T> = {
  // Base query state
  originalArgs?: unknown // Arguments passed to the query
  data?: T // The latest returned result regardless of hook arg, if present
  currentData?: T // The latest returned result for the current hook arg, if present
  error?: unknown // Error result if present
  requestId?: string // A string generated by RTK Query
  endpointName?: string // The name of the given endpoint for the query
  startedTimeStamp?: number // Timestamp for when the query was initiated
  fulfilledTimeStamp?: number // Timestamp for when the query was completed

  // Derived request status booleans
  isUninitialized: boolean // Query has not started yet.
  isLoading: boolean // Query is currently loading for the first time. No data yet.
  isFetching: boolean // Query is currently fetching, but might have data from an earlier request.
  isSuccess: boolean // Query has data from a successful load.
  isError: boolean // Query is currently in an "error" state.

  refetch: () => QueryActionCreatorResult // A function to force refetch the query - returns a Promise with additional methods
}

Example usage:

interface MyError {
  status: number;
  data: {
    status: string;
    message: string;
  };
}
const {
  data,
  isLoading,
  error
} = useGetUserInfoQuery();

...

(error as MyError).data.message;