Utilizing the error object in API response through the Slice Redux Toolit

I'm dealing with a particular situation involving some code:

 ...
    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',
            }
        }),
...

Here's where things start to get complicated:

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

When the error occurs, it contains the following information:

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

The issue arises when trying to access data.message in error:

error.data.message

This results in a TypeScript compiler error:

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

Even attempts like error!!.data!!.message!! do not work. So how can I successfully access data.message in error?

Answer №1

The error type is unknown, so it will need to be cast to an appropriate type in order to access specific properties.

Refer to the declarations for the useQuery hook:

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

type UseQueryResult<T> = {
  // Base query state
  originalArgs?: unknown
  data?: T
  currentData?: T
  error?: unknown
  requestId?: string
  endpointName?: string
  startedTimeStamp?: number
  fulfilledTimeStamp?: number

  // Derived request status booleans
  isUninitialized: boolean
  isLoading: boolean
  isFetching: boolean
  isSuccess: boolean
  isError: boolean

  refetch: () => QueryActionCreatorResult
}

Example usage:

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

...

(error as MyError).data.message;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What specific event do I require for the onChange event in React using TypeScript?

I'm facing a problem while working with React TypeScript. I need to type the onChange event for a select element, but the data is coming from event.value instead of event.target.value. What should be the appropriate event to use in this case? Below i ...

Encountering Problem with NextJS and Typescript when Attempting to Import Protected Authentication to a Page

When I try to use my protected.tsx file on a page, I encounter an error message stating: Server Error Error: Attempted to call the default export of protected.tsx from the server, but it should only be used on the client side. Invoking a client function ...

Issues persist with @typescript-eslint/no-unused-vars not functioning as expected

.eslintrc.json: { "root": true, "ignorePatterns": ["projects/**/*"], "overrides": [ { "files": ["*.ts"], "extends": [ "eslint:recommended", ...

Navigating with Leaflet.PolylineMeasure in Angular app

The challenge I'm facing involves integrating the Leaflet.PolylineMeasure plugin into my Angular application, which is written in JavaScript. After attempting to npm install the library from https://www.npmjs.com/package/leaflet.polylinemeasure, I enc ...

The type '{} is not compatible with the type 'IProps'

In my current project, I am utilizing React alongside Formik and TypeScript. The code snippet below demonstrates my usage of the withFormik Higher Order Component (HOC) in my forms: import React from 'react'; // Libraries import........ import { ...

Uploading raw data to Firebase bucket

I am currently developing a nodejs/typescript application that leverages Firebase Functions, and I am facing a challenge with uploading a JSON object to a bucket. The issue arises from the fact that the JSON data is stored in memory and not as an actual fi ...

"Slumber" in the asynchronous loop execution with the "for await" syntax (ES2018)

I am currently using asynchronous iteration to retrieve items from DynamoDB. During each iteration, I perform several http requests. To control the flow of requests, I need to introduce a 1-second delay after each item is processed. I have attempted to use ...

Issue arises when the value becomes nonexistent following the execution of a

Having an issue with my code where I have one class with a function in it, and another class that imports the first class to use that function. However, after the function is executed, I am not getting the expected value. First class: export class MoveE ...

Error encountered: React Typescript does not support the "any" type in a template literal expression

I have been encountering an issue with my slider component in React Typescript. The error message I keep getting is related to the "Invalid type 'any' of template literal expression" specifically at the const fillWidth variable. I am struggling t ...

the process of accessing information from a service in an Angular Typescript file

After making a POST request using Angular's HTTP client, the response data can be accessed within the service. However, is there a way to access this data in the app.component.ts file? I am able to retrieve the response data within the service, but I ...

Error: Unable to locate module with associated type definitions when utilizing Typescript in Next.js

Currently, I am working on a next.js project that I'm attempting to integrate typescript into. The structure of my folders is organized as follows: api aggregation.ts interfaces index.ts components Component1 index.js index.module.css ...

Generic Type for Promise in Typescript

I have a sample Promise function that is shown below. When successful, it returns a number, and when unsuccessful, it returns a string. The compiler is asking me to specify some kind of generic type for the promise. In this scenario, what type should I s ...

Error: SvelteKit server-side rendering encountered a TypeError when trying to fetch data. Unfortunately, Express is not providing a clear TypeScript stack trace

I've been monitoring the logs of the SvelteKit SSR server using adapter-node. After customizing the server.js to utilize Express instead of Polka, I noticed some errors occurring, particularly when the fetch() function attempts to retrieve data from ...

Angular's custom validator consistently returns a null value

I need help with validating the uniqueness of a username field in a form where an administrator can create a new user. I have implemented a uniqueUserNameValidator function for this purpose, but it always returns null. I suspect that the issue lies in the ...

Utilizing Window function for local variable assignment

Currently, I am facing a challenge in my Angular2 service where I am attempting to integrate the LinkedIN javascript SDK provided by script linkedin. The functionality is working as expected for retrieving data from LinkedIN, however, I am encountering an ...

Creating an array in TypeScript that supports multiple possible types, recursively, and enforces that all elements must be of the same type

I've been having difficulty creating a type that fits this specific data model: Each node can be: - native type - string, number, boolean, null, undefined - a list containing all the *same type* of nodes - a dictionary of any type of nodes ...

Why do users struggle to move between items displayed within the same component in Angular 16?

Lately, I've been immersed in developing a Single Page Application (SPA) using Angular 16, TypeScript, and The Movie Database (TMDB). During the implementation of a movies search feature, I encountered an unexpected issue. Within the app\servic ...

Transferring data from index.ts using export and import operations

While working on my angular project, I encountered a rather peculiar issue. I have organized my project into separate modules for layouts, login, and dashboard. Specifically for the login page, I wanted to implement a unique layout. Here's how I tried ...

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

Running out of memory due to inefficient mark-compacting processes nearing the heap limit in Angular 8 allocation

A significant portion of the modules are built, with only one active in progress. The process is located at ...\src\index.js??extracted!D:\Clients\app\node_modules\sass-loader\lib\loader.js??ref--15-3!D:\src&bso ...