Updating data with axios

Let's move on to updating data now. We are going to allow the user to click an Update button in an existing post to change and save it:

  1. Let's first create an Update 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>
</li>
  1. We can now implement the Update button click handler, which sets the post being edited in the component state:
private handleUpdateClick = (post: IPost) => {
this.setState({
editPost: post
});
};
  1. In our existing save click handler, we need two branches of code now for the existing POST request and the PUT request we need to implement:
private handleSaveClick = () => {
if (this.state.editPost.id) {
// TODO - make a PUT request
} else {
axios
.post<IPost>( ... )
.then( ... );
}
};
  1. Let's implement the PUT request now:
if (this.state.editPost.id) {
axios
.put<IPost>(
`https://jsonplaceholder.typicode.com/posts/${
this.state.editPost.id
}`,
this.state.editPost,
{
headers: {
"Content-Type": "application/json"
}
}
)
.then(() => {
this.setState({
editPost: {
body: "",
title: "",
userId: 1
},
posts: this.state.posts
.filter(post => post.id !== this.state.editPost.id)
.concat(this.state.editPost)
});
});
} else {
...
}

So, we filter out and concatenate the updated post to create a new posts array for the state.

The structure of the put function call is very similar to get and post.  Again, we could add error handling, a timeout, and the ability to cancel the request in the same way as we did for get.

In the running app, if we click an Update button in a post, change the title and body, and click the Save button, we see it removed from where it was and added to the bottom of the posts list with the new title and body.

If we want to PATCH a post, we can use the patch axios method. This has the same structure as put but instead of passing the whole object that is being changed, we can just pass the values that need updating.

In the next section, we will allow users to delete posts.

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

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