DEV Community

With Code Example
With Code Example

Posted on • Originally published at javascript.withcodeexample.com

How To Use React With Axios For Efficient Data Fetching

Hello, Welcome to my blog. In this React JS tutorial, we will learn what is axios. how we can use it with react Js to make API calls with the backend. Then we will see the examples to perform the GET, POST, PUT and DELETE requests with code examples.

What is Axios

Axios is a promise-based HTTP client library that is used to make API calls in the React JS application. With Axios you can perform all kinds of rest API request calls such as get, post, put and delete. It provides a cleaner and more intuitive way to fetch API for tasks like:

  • Fetching data from the server
  • Sending data to servers
  • Handling responses

Install Axios

We can use npm or yarn to install the Axios to our react app:

# using NPM
npm install axios

# using yarn
yarn add axios
Enter fullscreen mode Exit fullscreen mode

Making GET request with Axios

Get HTTP request is used to retrieve the data from the server, Axios provides a simple way to perform the HTTP GET operation.

Axios HTTP GET example

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

function App() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        setData(response.data);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      <h1>HTTP GET Example using Axios in React</h1>
      {loading ? (
        <p>Loading...</p>
      ) : error ? (
        <p>Error: {error.message}</p>
      ) : (
        <div>
          <h2>Data:</h2>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      )}
    </div>
  );
}
export default App;

Enter fullscreen mode Exit fullscreen mode

Making POST request with Axios

HTTP POST request is used to send the data to server, Axios provides a simple way to perform the HTTP POST operation.

Axios HTTP POST example

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

function App() {
  const [formData, setFormData] = useState({
    title: '',
    body: ''
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post('https://jsonplaceholder.typicode.com/posts', formData);
      console.log('Response:', response.data);
      setFormData({
        title: '',
        body: ''
      });
      alert('Post submitted successfully!');
    } catch (error) {
      console.error('Error submitting post:', error);
      alert('An error occurred while submitting the post. Please try again later.');
    }
  };

  return (
    <div>
      <h1>HTTP POST Example using Axios in React</h1>
      <form onSubmit={handleSubmit}>
        <div>
          <label>Title:</label>
          <input
            type="text"
            name="title"
            value={formData.title}
            onChange={handleChange}
            required
          />
        </div>
        <div>
          <label>Body:</label>
          <textarea
            name="body"
            value={formData.body}
            onChange={handleChange}
            required
          />
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Making PUT request with Axios

The PUT request is an HTTP request method for creating a new element or replacing the representation of an existing item with the request payload.

Axios HTTP PUT example

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

function App() {
  const [updatedData, setUpdatedData] = useState({
    id: 1,
    title: 'Updated Title',
    body: 'Updated Body'
  });

  const [responseData, setResponseData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const updateData = async () => {
      try {
        const response = await axios.put('https://jsonplaceholder.typicode.com/posts/1', updatedData);
        setResponseData(response.data);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    updateData();
  }, [updatedData]);

  return (
    <div>
      <h1>HTTP PUT Example using Axios in React</h1>
      {loading ? (
        <p>Loading...</p>
      ) : error ? (
        <p>Error: {error.message}</p>
      ) : (
        <div>
          <h2>Response Data:</h2>
          <pre>{JSON.stringify(responseData, null, 2)}</pre>
        </div>
      )}
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Making DELETE request with Axios

HTTP DELETE request is used to remove the data, Axios provides a simple way to perform the HTTP DELETE operation.

Axios HTTP DELETE example

import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
  const [responseData, setResponseData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const deleteData = async () => {
      try {
        const response = await axios.delete('https://jsonplaceholder.typicode.com/posts/1');
        setResponseData(response.data);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };
    deleteData();
  }, []);

  return (
    <div>
      <h1>HTTP DELETE Example using Axios in React</h1>
      {loading ? (
        <p>Loading...</p>
      ) : error ? (
        <p>Error: {error.message}</p>
      ) : (
        <div>
          <h2>Response Data:</h2>
          <pre>{JSON.stringify(responseData, null, 2)}</pre>
        </div>
      )}
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Thank you for reading our blog! We hope it was helpful and interesting. If you found something useful in what you read, we would be very happy if you could spread this information on social media. This way, we enlarge our reader’s base and disseminate valuable knowledge to a larger population. Thank you again for your support!

Top comments (0)