REST API consume in React

Posted on January 2, 2023
React

To consume a REST API in React, you can use the fetch function, or a library like axios to make HTTP requests to the API endpoint.

Here is an example using fetch to make a GET request to the JSONPlaceholder API to retrieve a list of users:

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

function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(data => setUsers(data));
  }, []);

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}
 

This code uses the useState and useEffect hooks to fetch the data and store it in the users state variable. The useEffect hook is used to perform the fetch when the component mounts, and the response is then parsed and set as the value of users.

You can also use axios to make the request, like this:

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

function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(response => setUsers(response.data));
  }, []);

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}
 

In both examples, the data is displayed in a list using the map function to iterate over the array of users.