How to call a REST API with REACT and Typescript using Axios Library

In this example, I will show you how to call a REST API using the popular Axios library with React and TypeScript. First, you need to install Axios:

npm install axios

Or if you are using Yarn:

yarn add axios

Now, let’s create a simple React component that fetches data from a REST API and displays it. For this example, we will use the JSONPlaceholder API, which provides sample data.

Create a new file called ApiComponent.tsx and add the following code:

import React, { useEffect, useState } from 'react';
import axios from 'axios';

// Define the type for the fetched data
interface Album {
  userId: number;
  id: number;
  title: string;
}

const ApiComponent: React.FC = () => {
  const [albums, setAlbums] = useState<Album[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get<Album[]>('https://jsonplaceholder.typicode.com/albums');
        setAlbums(response.data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      <h1>Albums</h1>
      <ul>
        {albums.map((album) => (
          <li key={album.id}>
            <h2>{album.title}</h2>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default ApiComponent;

In this example, we:

  1. Import the necessary React hooks and Axios.
  2. Define an interface Album to represent the data structure we expect to receive from the API.
  3. Create a functional React component ApiComponent.
  4. Use the useState hook to create a state variable albums and a corresponding setter setAlbums.
  5. Use the useEffect hook to fetch data from the API when the component mounts. Inside the effect, we define an async function fetchData that calls the API using Axios.
    • If the request is successful, we update the albums state with the received data.
    • If there’s an error, we log the error message to the console.
  6. Render the fetched albums in a list.
  7. Export the component for use in other parts of the application.

To use this component, simply import it and include it in your main application or another component:

import React from 'react';
import ApiComponent from './ApiComponent';

const App: React.FC = () => {
  return (
    <div>
      <ApiComponent />
    </div>
  );
};

export default App;

Now, when the ApiComponent the component is rendered, it will fetch data from the JSONPlaceholder API and display the fetched albums.


Posted

in

by