Skip to main content

Connect to an API on React

To connect to an API with React, you can use the Fetch library, which is included in React by default, or a third-party library such as Axios. Here is sample code that demonstrates how to use Fetch to connect to an API and retrieve data:


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

const App = () => {
const [data, setData] = useState(null);

useEffect(() => {
// Appeler l'API lorsque le composant est monté
fetch('https://my-api.com/endpoint')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error(error));
}, []);

// Afficher les données de l'API une fois qu'elles sont disponibles
return data ? <p>{data}</p> : <p>Loading...</p>;
};

export default App;

This code uses React's useEffect function to make an API call when the component is mounted.

  • The fetch function is used to send a request to the API
  • then the response is transformed into JSON and stored in the local state of the component using the setData function.
  • Finally, data is displayed in the component rendering when available.