GET, POST, PUT, DELETE Requests with Axios in React JS
Axios is a powerful library for making HTTP requests in JavaScript. In this article, we will demonstrate how to make GET
, POST
, PUT
, and DELETE
requests using Axios in a React application.
GET Request
A GET
request is used to retrieve data from a server. Below is an example of a GET
request:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function GetRequest() {
const [data, setData] = useState(null);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => setData(response.data))
.catch(error => console.error('Error fetching data:', error));
}, []);
return (
GET Request Example
{data ? (
Title: {data.title}
Body: {data.body}
) : (
Loading...
)}
);
}
export default GetRequest;
POST Request
A POST
request is used to send data to the server. Below is an example:
import React, { useState } from 'react';
import axios from 'axios';
function PostRequest() {
const [response, setResponse] = useState(null);
const handlePost = () => {
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'New Post',
body: 'This is the content of the new post.',
userId: 1
})
.then(res => setResponse(res.data))
.catch(error => console.error('Error posting data:', error));
};
return (
POST Request Example
{response && (
Post Created: {JSON.stringify(response)}
)}
);
}
export default PostRequest;
PUT Request
A PUT
request is used to update existing data. Below is an example:
import React, { useState } from 'react';
import axios from 'axios';
function PutRequest() {
const [response, setResponse] = useState(null);
const handleUpdate = () => {
axios.put('https://jsonplaceholder.typicode.com/posts/1', {
title: 'Updated Title',
body: 'Updated body content.',
userId: 1
})
.then(res => setResponse(res.data))
.catch(error => console.error('Error updating data:', error));
};
return (
PUT Request Example
{response && (
Post Updated: {JSON.stringify(response)}
)}
);
}
export default PutRequest;
DELETE Request
A DELETE
request is used to remove data from the server. Below is an example:
import React, { useState } from 'react';
import axios from 'axios';
function DeleteRequest() {
const [response, setResponse] = useState(null);
const handleDelete = () => {
axios.delete('https://jsonplaceholder.typicode.com/posts/1')
.then(res => setResponse('Post deleted successfully.'))
.catch(error => console.error('Error deleting data:', error));
};
return (
DELETE Request Example
{response && (
{response}
)}
);
}
export default DeleteRequest;
Summary
Using Axios in React makes HTTP requests simple and efficient. You can use the GET
method to retrieve data, POST
to create new data, PUT
to update existing data, and DELETE
to remove data. Axios provides a clean and consistent API to handle these operations with ease.