There is generic get method defined in axios/index.d.ts

get<T = never, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig<T>): Promise<R>;

Example

interface User {
    id: number;
    firstName: string;
}


axios.get<User[]>('http://localhost:8080/admin/users')
        .then(response => {
            console.log(response.data);
            setUserList( response.data );
        });

I think you are passing list the wrong way to child component.

const [users, setUserList] = useState<User[]>([]);
<UserList items={users} />
interface UserListProps {
    items: User[];
};
const UserList: React.FC<UserListProps> = ({items}) => {
    return (
        <Fragment>
            <ul>
            {items.map(user => (
                <li key={user.id}>
                    <span>{user.firstName}</span>
                </li>
            ))}
            </ul>
        </Fragment>
    );
};
Answer from Józef Podlecki on Stack Overflow
Top answer
1 of 2
136

There is generic get method defined in axios/index.d.ts

get<T = never, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig<T>): Promise<R>;

Example

interface User {
    id: number;
    firstName: string;
}


axios.get<User[]>('http://localhost:8080/admin/users')
        .then(response => {
            console.log(response.data);
            setUserList( response.data );
        });

I think you are passing list the wrong way to child component.

const [users, setUserList] = useState<User[]>([]);
<UserList items={users} />
interface UserListProps {
    items: User[];
};
const UserList: React.FC<UserListProps> = ({items}) => {
    return (
        <Fragment>
            <ul>
            {items.map(user => (
                <li key={user.id}>
                    <span>{user.firstName}</span>
                </li>
            ))}
            </ul>
        </Fragment>
    );
};
2 of 2
16

You need to provide a type argument when calling axios.get if you do not want Axios to infer the type for the value response as any.

And you are passing an incorrect type argument when you useState to create the array of users.

The correct way

interface User {
  id: number;
  firstName: string;
}

// Initialized as an empty array
const [users, setUserList] = useState<User[]>([]); // 'users' will be an array of users

For example,

import React, {useEffect, useState, Fragment } from 'react';
import UserList from './UserList';
import axios from 'axios';

interface User {
  id: number;
  firstName: string;
}

// You can export the type TUserList to use as -
// props type in your `UserList` component
export type TUserList = User[]

const Users: React.FC = (props) => {
   // You can also use User[] as a type argument
    const [users, setUserList] = useState<TUserList>();

    useEffect(() => {
        // Use [] as a second argument in useEffect for not rendering each time
        axios.get<TUserList>('http://localhost:8080/admin/users')
        .then((response) => {
            console.log(response.data);
            setUserList(response.data);
        });
    }, []);

    return (
        <Fragment>
            <UserList {...users} />
        </Fragment>

    );
};
export default Users;

If you choose to export the type type TUserList = User[], you can use it in your UserList component as the type for props. For example,

import React, {Fragment } from 'react';
import { TUserList } from './Users';

interface UserListProps {
    items: TUserList // Don't have to redeclare the object again
};

const UserList: React.FC<UserListProps> = (props) => {
    return (
        <Fragment>
            <ul>
            {props.items.map(user => (
                <li key={user.id}>
                    <span>{user.firstName}</span>
                    { /* Do not call the delete function. Just point
                         to it. Set this to null in bind(). */}
                </li>
            ))}
            </ul>
        </Fragment>
    );
};

export default UserList;
🌐
DEV Community
dev.to › mdmostafizurrahaman › handle-axios-error-in-typescript-4mf9
Handle Axios Error in Typescript - DEV Community
December 23, 2022 - By asserting type you are forcing the typescript to stop doing his work. So this may be problematic sometimes. We can use typeguard to handle this kind of situation and axios also provides a typeguard for handling errors. Here how it looks like · const fetchPosts = async () => { try { const response = await axios.get( "<https://jsonplaceholder.typicode.com/posts>" ); // Do something with the response } catch (error) { if (axios.isAxiosError(error)) { console.log(error.status) console.error(error.response); // Do something with this error...
Discussions

How to Type Axios.js 'AxiosResponse' data generic
axios.get()? More on reddit.com
🌐 r/typescript
6
6
August 4, 2021
Typescript With Axios Response - Stack Overflow
Working with Typescript while making an API call with axios and have come across a nested data scenario. Although I believe to have it typed correctly, I keep receiving a Typescript error stating U... More on stackoverflow.com
🌐 stackoverflow.com
Typescript + axios: return the subset of response
TypeScript types have no meaning at runtime and they get removed. Just because you say it's IApiResponse at compile time doesn't mean it is, and TypeScript definitely doesn't help you parse an object at runtime in any way. You'll need to manually select the data you want from the response. More on reddit.com
🌐 r/typescript
3
1
August 14, 2023
reactjs - How to solve TypeScript error with axios response in React app - Stack Overflow
I've got the following React function (using the alpha of React Hooks) that has a TypeScript error (thought it still works). The error is pointing to the line of code where the axios promise compl... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com › axios › axios › issues › 1510
How to use Axios with TypeScript when using response interceptors (AxiosResponse issue) · Issue #1510 · axios/axios
April 30, 2018 - Summary In a project I am migrating to TypeScript (TS), I have a response interceptor r => r.data. How do I inform TS that I am not expecting a type of AxiosResponse? I've tried overriding using as...
Author   rssfrncs
🌐
Reddit
reddit.com › r/typescript › how to type axios.js 'axiosresponse' data generic
r/typescript on Reddit: How to Type Axios.js 'AxiosResponse' data generic
August 4, 2021 -

Hi all!

I'm using the axios http library for Node to make requests to a public API as follows:

const response = await axios.get(url)

logPaginatedResponse(response)

After receiving a response and storing it in the response variable above, I am passing the variable to the logPaginatedResponse function to log the response to the console.

My logPaginatedResponse function looks like this:

import { AxiosResponse } from "axios"

export const logPaginatedResponse = async (response: AxiosResponse) => {
  console.dir({
    total_records: response.data.meta.pagination.total,
    records_per_page: response.data.meta.pagination.per_page,
    current_page: response.data.meta.pagination.current_page,
    total_pages: response.data.meta.pagination.total_pages,
  })
}

The AxiosResponse interface looks like this:

export interface AxiosResponse<T = any>  {
  data: T;
  status: number;
  statusText: string;
  headers: any;
  config: AxiosRequestConfig;
  request?: any;
}

In the logPaginatedResponse, I am trying to get autocompletion for response.data.meta.pagination.total, response.data.meta.pagination.per_page, etc.

The AxiosResponse interface gives me autocompletion for response, but no autocompletion for anything in the data object.

The problem is, the data object on the response could be one of many interfaces. See below:

interface CustomerResponse {
  data: {
    customer_id: number
  },
  meta: {
    pagination: {
      total: number,
      count: number,
      per_page: number,
      current_page: number,
      total_pages: number,
      links: {
        previous: string,
        current: string,
        next: string
      }
    }
  },
}

interface ProductResponse {
  data: {
    product_id: number
  },
  meta: {
    pagination: {
      total: number,
      count: number,
      per_page: number,
      current_page: number,
      total_pages: number,
      links: {
        previous: string,
        current: string,
        next: string
      }
    }
  },
}

export const logPaginatedResponse = async (response: AxiosResponse<CustomerResponse | ProductResponse>) => { // console.dir here }

Is there any way to give logPaginatedResponse either the CustomerResponse or ProductResponse interface dynamically?

I tried passing CustomerResponse or ProductResponse to the logPaginatedResponse function at the time of function invocation as follows:

const response = await axios.get(url)

logPaginatedResponse<CustomerResponse>(response)

But that isn't doing the trick. Is this not possible? It almost sounds like I'm looking for what this SO post describes: https://stackoverflow.com/a/50512697 but I'm not entirely sure.

Any suggestions would be super appreciated!! Thank you so much.

EDIT:

I ended up refactoring per u/__gc's suggestion in the comments

🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-http-request-axios
Making HTTP requests with Axios in TypeScript | bobbyhadz
February 27, 2024 - What you might have noticed is that axios automatically parses the JSON from the response as opposed to the built-in fetch() method. We directly have the parsed response stored in the data variable.
🌐
Delft Stack
delftstack.com › home › howto › typescript › axios typescript
How to Use Axios in TypeScript | Delft Stack
February 2, 2024 - The above types can make typed REST API calls in TypeScript. Suppose an e-commerce website makes a REST API call to its backend to show all the books available on its frontend. interface Book { isbn : string; name : string; price : number; author : string; } axios.get<Book[]>('/books', { baseURL : 'https://ecom-backend-example/api/v1', }).then( response => { console.log(response.data); console.log(response.status); })
🌐
Geshan
geshan.com.np › blog › 2023 › 11 › axios-typescript
How to use Axios with Typescript a beginner’s guide
November 7, 2023 - That covers the basics of using Axios with TypeScript to make API calls and handle the response data. You have learned the basics of Axios and its types for making a GET and a POST call in a TypeScript environment. The example is executed on a Node.js environment but it should work the same on a browser too as Axios runs on both the server and the client.
Find elsewhere
🌐
Medium
medium.com › @dingezzz › basic-requests-with-axios-in-typescript-5f52dea8ec9a
Basic requests with Axios in TypeScript | by Bas den Burger | Medium
January 16, 2023 - The then method is called on the promise returned by the get method, and the callback function passed to then receives the response object. The response object contains a data property, which is typed as the Response interface defined earlier.
🌐
Upmostly
upmostly.com › home › typescript › how to use axios
How to Use Axios in Your TypeScript Apps - Upmostly
December 8, 2022 - At the moment our response has the type any. TypeScript doesn’t know what properties it has, and neither do we. Thankfully the Axios methods are generic, so let’s build some types for our response.
🌐
Revathskumar
blog.revathskumar.com › 2023 › 04 › typescript-add-types-for-axios-response-data-and-error-data.html
TypeScript: add types for axios response data and error data
April 17, 2023 - And TS will throw error if we try to use a non-existing key like response.data.stats. ... In TS, the error we receive in try...catch block will always have type unknown. So we won’t be able to assign type in catch instead we have to define new variable. import axios, { AxiosError, isAxiosError } from 'axios'; type PostHelloErrorType = { status: string; message: string; type: string; errors: string[]; }; async function postHello() { try { // call axios methods } catch (error) { if (isAxiosError(error)) { const err: AxiosError<PostHelloErrorType> = error; console.log(err.response.data.message); } } }
🌐
LinkedIn
linkedin.com › pulse › mastering-http-requests-javascript-axios-typescript-novin-noori
Mastering HTTP Requests in JavaScript with Axios and TypeScript
March 15, 2023 - We're accessing the response data using response.data, transforming it however we want, and then assigning the transformed data back to response.data. Cancelling requests can be helpful in situations where a user navigates away from a page or updates a filter before the previous request has been completed. This prevents unnecessary API calls and can improve performance. Here's an example of how to use Axios to cancel a request:
🌐
DEV Community
dev.to › limacodes › why-using-axios-with-typescript-1fnj
Why using AXIOS with Typescript? - DEV Community
February 10, 2023 - It automatically converts the response to JSON and has built-in mechanisms for handling errors, making it easier to work with and less prone to bugs. This can result in faster development times and less time spent debugging.
🌐
Medium
dpw-developer.medium.com › your-first-api-call-get-requests-in-typescript-using-axios-b374be0479b6
Your First API Call: GET Requests in Typescript using Axios | by Daniel Wilkinson | Medium
January 13, 2025 - import axiosRetry from 'axios-retry'; ... if we need to handle an axios error in typescript we can use AxiosError as the type to safely access the properties in the catch....
🌐
Apidog
apidog.com › blog › axios-typescript
How to Use Axios and Typescript to Build APIs
May 13, 2024 - You can also avoid the hassle of manually defining and casting the types of the response data, and rely on the type inference and generics of typescript. Axios-typescript also supports all the features and options of axios, such as interceptors, cancelations, timeouts, etc.
🌐
Reddit
reddit.com › r/typescript › typescript + axios: return the subset of response
r/typescript on Reddit: Typescript + axios: return the subset of response
August 14, 2023 -

Hi all, Noobie here,

So, I am using axios with typescript. I am calling get method on the axios and it returns whole bunch of data but I only need fraction of those data as following:

Interface IApiResponse{ // Small punch of types API returns name:strong Age:number } const response = axios.get<IApiResponse>(URL)

Now, my noob question is why is the response contains additional data as well; one which is not defined in the IApiResponse. For example, API response contains address as well but I have not defined that type in IApiResponse.

How can I only select few data that I need to be included in interface?

Thank you for the help ☺️☺️

🌐
DhiWise
dhiwise.com › post › exploring-the-possibilities-of-axios-with-typescript
Exploring the Possibilities of Axios with Typescript
November 2, 2023 - With TypeScript, you can define clear interfaces and types for your Axios requests and responses, enabling seamless collaboration within your development team.
Top answer
1 of 1
16

The reason is in this line:

const [data, setData] = useState(null)

Because there is no type parameter provided explicitly for useState, TypeScript infers the type of data based on the type of initial state. In this case, the initial state is null and TypeScript treats this type as the only possible state.

You know that the state will either be null or something else — but TypeScript doesn't. Let's use type parameters to tell it what's really going on.

const [data, setData] = useState<AxiosResponse | null | void>(null);

This gets rid of the error, but looks strange — why is void there? The reason for that is that you catch before you then — and since catch emits a side effect (returns void, in other words), the type propagated to catch is either void or AxiosResponse. Let's fix that by replacing then and catch.

The final solution:

import axios, { AxiosResponse } from "axios";
import { useEffect, useState } from "react";

const useAxiosFetch = (url: string, timeout: number) => {
  const [data, setData] = useState<AxiosResponse | null>(null);
  const [error, setError] = useState(false);
  const [errorMessage, setErrorMessage] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let unmounted = false;
    const source = axios.CancelToken.source();
    axios
      .get(url, {
        cancelToken: source.token,
        timeout,
      })
      .then(a => {
        if (!unmounted) {
          setData(a);
          setLoading(false);
        }
      })
      .catch(function(e) {
        if (!unmounted) {
          setError(true);
          setErrorMessage(e.message);
          setLoading(false);
          if (axios.isCancel(e)) {
            console.log(`request cancelled:${e.message}`);
          } else {
            console.log("another error happened:" + e.message);
          }
        }
      });

    return function() {
      unmounted = true;
      source.cancel("Cancelling in cleanup");
    };
  }, []);

  return { data, loading, error, errorMessage };
};

export default useAxiosFetch;

🌐
GitHub
gist.github.com › JaysonChiang › fa704307bacffe0f17d51acf6b1292fc
Example of Axios with TypeScript · GitHub
@jdriesen This is an example of using axios library. interceptors.request is used to add to each request a Auth header with token. It's part of JWT auth. interseptors.response is used to handle error if some exist after each request. After there ...
🌐
TestMu AI Community
community.testmuai.com › ask a question
Handling Axios Responses in TypeScript for User List Rendering - TestMu AI Community
November 4, 2024 - How do I handle Axios responses with TypeScript when rendering a user list? I’m working on a React and TypeScript project where I need to present a simple user list fetched from an API. The API returns data in the following format: [{“UserID”:2,“FirstName”:“User2”},{“UserID”:1,“FirstName”:“User1”}] However, I am encountering the TypeScript error: “Type ‘{} | { id: number; firstName: string; }’ is not assignable to type ‘IntrinsicAttributes & UserListProps & { children?: ReactNode; }’. Proper...