Milind Daraniya

Solving TypeScript Error with Axios Response in a React App - A Step-by-Step Guide

Published October 24th, 2023 16 min read

Hello React developers! 👋

Are you working with TypeScript in a React app and encountering errors when dealing with Axios responses? Fear not, let's navigate through the process of handling TypeScript errors associated with Axios responses in a React application with a practical example.

1. Install Axios and TypeScript:

Make sure you have Axios and TypeScript installed in your React project:

npm install axios
npm install --save-dev typescript @types/node @types/react @types/react-dom @types/jest

2. Create a Sample API and TypeScript File:

For this example, let's assume you have a simple JSONPlaceholder API endpoint. Create a TypeScript file named api.ts:

// api.ts
import axios, { AxiosResponse } from 'axios';

const fetchData = async () => {
  try {
    const response: AxiosResponse = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
    return response.data;
  } catch (error) {
    throw new Error(error.message);
  }
};

export default fetchData;

3. Define a Component Using the API:

Now, let's create a React component (App.tsx) that uses the API we defined in api.ts:

// App.tsx
import React, { useEffect, useState } from 'react';
import fetchData from './api';

const App: React.FC = () => {
  const [data, setData] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchDataAsync = async () => {
      try {
        const result = await fetchData();
        setData(result);
      } catch (error) {
        setError(error.message);
      }
    };

    fetchDataAsync();
  }, []);

  return (
    <div>
      {data ? (
        <div>
          <h1>Data Received:</h1>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      ) : error ? (
        <h1>Error: {error}</h1>
      ) : (
        <h1>Loading...</h1>
      )}
    </div>
  );
};

export default App;

4. Resolve TypeScript Error:

In TypeScript, Axios responses include generic types to represent the response data. Update your api.ts file to correctly handle the response:

// api.ts
import axios, { AxiosResponse } from 'axios';

interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

const fetchData = async (): Promise<Todo> => {
  try {
    const response: AxiosResponse<Todo> = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
    return response.data;
  } catch (error) {
    throw new Error(error.message);
  }
};

export default fetchData;

5. Run Your React App:

Start your React app and see the TypeScript error resolved:

npm start

6. Explore and Customize:

Feel free to explore and customize the code based on your project requirements. This example demonstrates handling TypeScript errors with Axios responses in a React app efficiently.