Back to all posts

Sending HTTP Requests in React JS


HTTP requests are an integral part of web developments. React, being a frontend library, doesn’t have native support for sending HTTP requests. However, it can be combined with other libraries such as Fetch API , Axios to send HTTP requests.

In below content we demonstrated how to connect to a database or any other server-side resource.

Fetch API

Fetch API provides a fetch() method defined on the window object. You can use it to send requests.

Fetch returns promises and uses the Promise API for handling response and errors. for handling success wen can use .then() and for failure of request you can use .catch()

Get Request using Fetch API

Here’s an example of how we can make a GET request using Fetch API in a functional component using React hooks:

import {useEffect, useState} from 'react';

function App(){
     const [data, setData] = useState([]);
     useEffect(() => {
          fetch('url')
             .then(response => response.json())
             .then(data => setData(data))
             .catch(error => console.error('Error: ', error));
     }, []);
     
     return (
          // ... JSX HERE
     );
}

export default App;

For POST requests, you can pass an options object to the fetch() function with the method property set to ‘POST’, and a body property containing the data you want to send:

handleSubmit = (e) => {
  e.preventDefault();

  fetch('https://jsonplaceholder.typicode.com/posts', {
     method: 'POST',
     body: JSON.stringify({
        title: this.state.title,
        body: this.state.body,
        userId: Math.random().toString(36).slice(2),
     }),
     headers: {
        'Content-type': 'application/json; charset=UTF-8',
     },
  })
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.log(error));
};

https://gh6rd7-5173.csb.app/

Axios

Axios is a popular, promise-based HTTP client that provides a simple and cleaner API for making HTTP requests. it can be used in both class-based and functional components.

Here’s an example of a GET request using Axios in a functional component:

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

const App = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
     axios.get('https://jsonplaceholder.typicode.com/posts')
        .then((response) => {
           setPosts(response.data);
        })
        .catch((error) => {
           console.log(error);
        });
  }, []);

  return (
     // ... consume here
  );
};

Making a POST request: Similarly, you can make POST request usign the `.post()` method. Here’s an example of a POST request:

import axios from "axios";
import React from "react";
const baseURL = "https://jsonplaceholder.typicode.com/posts";
export default function App() {
  const [post, setPost] = React.useState(null);
  React.useEffect(() => {
    axios.get(`${baseURL}/1`).then((response) => {
      setPost(response.data);
    });
  }, []);
  function createPost() {
    axios
      .post(baseURL, {
        title: "Hello World!",
        body: "This is a new post."
      })
      .then((response) => {
        setPost(response.data);
      });
  }
  if (!post) return "No post!"
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
      <button onClick={createPost}>Create Post</button>
    </div>
  );
}

Check more detailed Axios reference

https://www.freecodecamp.org/news/axios-react-how-to-make-get-post-and-delete-api-requests/