How to Get Data From an API in React.js?
Tags: javascript, react, api, programming
Published: 2023-07-26 04:36:54

API stands for Application Programming Interface. It is a set of rules and protocols that allows different software applications to communicate and interact with each other. APIs define the methods and data formats that applications can use to request and exchange information.

In the context of web development and React, APIs are often used to connect front-end applications (built with React.js) with back-end servers or third-party services. React.js is primarily a front-end library, responsible for rendering user interfaces and managing the reusable UI components.

## How APIs work with React.js?
### Request
When a React application needs to fetch data from a server or a third-party service, it sends an HTTP request to a specific API endpoint, usually a **GET** request to get data, a **POST** request to save or [upload a file](https://devhubby.com/thread/how-to-upload-a-file-in-react-js), a **DELETE** request to delete data, a **PUT** request to update the entire resource with data that is passed in the body payload, or a PATCH request for partial modifications to a resource.

### Server/Service
The API endpoint on the server or the third-party service processes the incoming request. It performs the required operations (e.g., accessing a database, performing calculations, retrieving data) based on the request parameters and data.

### Response
After processing the request, the server sends back an HTTP response containing the requested data or the result of the operation. This response is typically in a standardized data format like JSON or XML.

### Data Handling in React
Once the React application receives the response from the API, it can parse the data (if it's in JSON or XML or whatever format) and use it to update the UI or perform any necessary actions based on the received information.

In React, you can use various methods and libraries to make API calls. For example, you can use the built-in fetch API, [axios](https://www.npmjs.com/package/axios), or async/await with fetch. Additionally, React provides lifecycle methods and hooks (e.g., [componentDidMount](https://react.dev/reference/react/Component#componentdidmount), [useEffect](https://react.dev/reference/react/useEffect)) that allow you to trigger API calls at specific points during the component lifecycle or when the component mounts.

## Example of how to fetch data from an API in React.js using fetch
```jsx
import React, { useState, useEffect } from 'react';

export const App = () => {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    // API call to get data
    fetch('https://dummyjson.com/products')
      .then(response => response.json())
      .then(data => setProducts(data.products))
      .catch(error => console.error('Error fetching data:', error));
  }, []);

  return (
    <div className="container">
      {products.map(product => (
          <div className="product" key={product.id}>
             <p><span>Name:</span> {product.title}</p>
             <p><span>Description:</span> {product.description}</p>
             <hr />
          </div>
        )
      )}
    </div>
  );
};
```

## Example of How to Fetch Data From an API in React.js using axios
```jsx
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

const App = () => {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    // API call to get data using axios
    axios.get('https://dummyjson.com/products')
      .then(response => {
        console.log(response)
        setProducts(response.data.products);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div className="container">
      {products.map(product => (
          <div className="product" key={product.id}>
             <p><span>Name:</span> {product.title}</p>
             <p><span>Description</span> {product.description}</p>
             <hr />
          </div>
        )
      )}
    </div>
  );
};

ReactDOM.createRoot( 
  document.querySelector('#root')
).render(<App />)
```