Deleting data with axios

Let's move on to deleting data now. We are going to allow the user to click a Delete button in an existing post to delete it:

  1. Let's first create a Delete button in each list item in the posts:
<li key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
<button onClick={() => this.handleUpdateClick(post)}>
Update
</button>
<button onClick={() => this.handleDeleteClick(post)}>
Delete
</button>
</li>
  1. We can now create the Delete button click handler:
private handleDeleteClick = (post: IPost) => {
axios
.delete(`https://jsonplaceholder.typicode.com/posts/${post.id}`)
.then(() => {
this.setState({
posts: this.state.posts.filter(p => p.id !== post.id)
});
});
};

So, we use the axios delete method to make an HTTP DELETE request, which follows the same structure as the other methods.

If we go to the running app, we should see a delete button in each post. If we click one of the buttons, we'll see it removed from the list after a short delay. 

So, that concludes this section on axios with class components. We've seen that the axios functions are a little cleaner than fetch, and features such as the ability to have typed responses, timeouts, and request cancellation make it a popular choice for many developers. In the next section, we'll refactor the App component we have just implemented to be a function component.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.196.59