react js contact with backend api using fetch()

Updated: Feb 15, 2025

react js contact with backend api using fetch()

To make contact with a backend API using React JS and the fetch() function, follow the steps below:

  1. First, ensure that you have set up your React project and have installed all necessary dependencies. If you are using Create React App, you can install axios or fetch as an alternative to fetch() by running the following command in your terminal:
npm install axios

or

npm install fetch
  1. Create a new component or use an existing one where you want to make the API call.

  2. Inside the component, create a new state variable to hold the data returned from the API. You can initialize it as an empty object or array.

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

const MyComponent = () => {
  const [data, setData] = useState({});

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    // API call using fetch() function
  };

  return (
    <div>
      {/* Render your component here */}
    </div>
  );
};

export default MyComponent;
  1. Inside the fetchData function, use the fetch() function to make the API call. You can provide the API endpoint as the first argument and set the headers and other options as the second argument.
const fetchData = async () => {
  try {
    const response = await fetch('https://api.example.com/data');
    const jsonData = await response.json();
    setData(jsonData);
  } catch (error) {
    console.log('Error:', error);
  }
};
  1. After making the API call, update the state variable using the setData() function.

  2. Finally, render the data in your component using the state variable.

return (
  <div>
    <h1>Data from API:</h1>
    <pre>{JSON.stringify(data, null, 2)}</pre>
  </div>
);

With these steps, you have successfully made contact with a backend API using React JS and the fetch() function. Note that you can modify the code to suit your specific use case, such as handling errors, loading states, and updating the UI based on the API response.