0

If I have a react view that requires two queries to be made from an RTKQuery cache/api calls, how can I combine the isLoading, error, etc?

I've thought of doing the following but I'm not sure how the error objects are composed

Could possibly write a special hook that does just this

const useUsersAndHousesQueries = () => {
    const users = useUsersQuery()
    const houses = useHousesQuery()

    const isLoading: boolean = users.isLoading || houses.isLoading
    const isError: boolean = users.isError || houses.isError
    // ...users || ...houses boolean values
    
    const data = {users: users.data, houses: houses.data}
    const error = {...} // How are RTKQuery's errors structured? Or do I structure them myself? Is it derived from the api call's response? I want to combine them so they can be rendered in an alert together in a component as a warning

    return {isLoading, isError, data, error, ...}
}

1 Answers1

1

If you are using fetchBaseQuery, it is either FetchBaseQueryError or (in very unexpected cases) a SerializedError:

In the case of a FetchBaseQueryError, data will be the response from the server (if available in some form)

export type FetchBaseQueryError =
  | {
      /**
       * * `number`:
       *   HTTP status code
       */
      status: number
      data: unknown
    }
  | {
      /**
       * * `"FETCH_ERROR"`:
       *   An error that occurred during execution of `fetch` or the `fetchFn` callback option
       **/
      status: 'FETCH_ERROR'
      data?: undefined
      error: string
    }
  | {
      /**
       * * `"PARSING_ERROR"`:
       *   An error happened during parsing.
       *   Most likely a non-JSON-response was returned with the default `responseHandler` "JSON",
       *   or an error occurred while executing a custom `responseHandler`.
       **/
      status: 'PARSING_ERROR'
      originalStatus: number
      data: string
      error: string
    }
  | {
      /**
       * * `"CUSTOM_ERROR"`:
       *   A custom error type that you can return from your `queryFn` where another error might not make sense.
       **/
      status: 'CUSTOM_ERROR'
      data?: unknown
      error: string
    }

export interface SerializedError {
  name?: string
  message?: string
  stack?: string
  code?: string
}
phry
  • 35,762
  • 5
  • 67
  • 81