Hi Developers,
Today we are going to learn how to use delete request using the axios library in react js. Axios is a npm package and the provide to make http request from your application
1) Initially we create a posts state
2) Use axios library inside componentDidMount() function which executes on page load and stores data in posts state
3) Onclicking delete button deleteRow(id, e) function is called and using the id it passes axios delete request
4) After deleting the data we remove the data from the posts state using filter
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 => {
const posts = res.data;
this.setState({ posts });
})
}
deleteRow(id, e){
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>
<h1>React Axios Delete Request Example - ITSolutionsGuides</h1>
<table className="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{this.state.posts.map((post) => (
<tr>
<td>{post.id}</td>
<td>{post.title}</td>
<td>{post.body}</td>
<td>
<button className="btn btn-danger" onClick={(e) => this.deleteRow(post.id, e)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
}
We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.
Be the first to know about releases and tutorial news and solutions.
We care about your data in our privacy policy.
ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.
Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides