React Axios DELETE Request: Deleting Data from APIs
Learn how to perform DELETE requests using Axios in your React applications. This tutorial demonstrates making DELETE requests to remove data from an API, handling responses, and updating the UI, providing a practical example for building interactive and data-driven React applications.
React Axios DELETE Request Example
Introduction to Axios DELETE Requests in React
This tutorial demonstrates how to make DELETE requests using Axios in a React application. We'll use the `jsonplaceholder` API for a practical example. Axios is a popular JavaScript library for making HTTP requests from the browser, simplifying interaction with external APIs.
Why Use Axios?
Axios simplifies making HTTP requests in JavaScript. It handles many common tasks, such as setting headers, handling errors, and working with promises. Its features are particularly helpful in React applications that frequently interact with backend APIs.
Example: Deleting a Post
This example shows how to make a DELETE request to remove a post from the `jsonplaceholder` API. Note: This API is just for demonstration and data deletion will not persist.
React Axios DELETE Request
import React from 'react';
import axios from 'axios';
export default class PostList extends React.Component {
state = { posts: [] };
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(res => {
this.setState({ posts: res.data });
});
}
deleteRow = (id) => {
axios.delete(`https://jsonplaceholder.typicode.com/posts/${id}`)
.then(res => {
console.log(res);
console.log(res.data);
const posts = this.state.posts.filter(item => item.id !== id);
this.setState({ posts });
});
};
render() {
return (
<div>
<h2>Example of React Axios DELETE Request</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.state.posts.map((post) => (
<tr key={post.id}>
<td>{post.id}</td>
<td>{post.title}</td>
<td>{post.body}</td>
<td>
<button onClick={() => this.deleteRow(post.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
This code fetches posts, then provides a button for each post that, when clicked, sends a DELETE request to the API to delete that post. The updated list is then re-rendered.