In the previous part of this Series. you learned how to add and display blog posts in a React application. In this section of the React blog app tutorial, we’ll dive into implementing the functionality to update and delete blog posts. Let’s start by cloning the source code from the previous part:
1. Clone the repository: `git clone https://github.com/royagasthyan/ReactBlogApp-AddPost`
2. Navigate to the project directory and install dependencies: `cd ReactBlogApp-AddPost` and `npm install`
3. Start the Node.js server; the app will run at `http://localhost:7777/index.htML#/`
### Creating Update and Delete Views
Modify the blog post list to display Data in a table format with update and delete icons. In the `ShowPost` component’s `render` method, replace the existing `div` with a `table`, as shown:
“`jsx
# | Title | Subject | ||
---|---|---|---|---|
{index + 1} | {post.title} | {post.subject} |
“`
Save these changes and restart the server. Access the browser at `http://localhost:7777/home#/` to view the blog post list in a tabular format.
To implement the update feature, attach a click event to the eDiT icon:
“`jsx
this.updatePost(post._id)} className=”glyPhi-con glyphicon-pencil”>
“`
In the `ShowPost` component, create an `updatePost` method:
“`jsx
updatePost(id) {
hashHistory.push(`/addpost/${id}`);
}
“`
Update the router to include an optional `id` parameter in the `AddPost` page:
“`jsx
“`
In the `AddPost` component, create a `getPostWithId` method to fetch the blog post detAIls using the ID:
“`jsx
getPostWithId() {
const id = this.props.params.id;
axios.post(“/getPostWithId”, { id }).then((response) => {
if (response) {
this.setState({ title: response.data.title });
this.setState({ subject: response.data.subject });
}
}).catch((error) => {
console.log(‘Error is’, error);
});
}
“`
Display the state variables’ values in the title and subject text boxes:
“`jsx
“`
Create the `getPostWithId` API in `app.js` to make a database call to fetch the post details with a specific ID. In `post.js`, create a `getPostWithId` method to query the database for the details.
### Updating Blog Posts
In `app.js`, modify the `addPost` API to check if the `id` exists. If it’s a new post, the `id` will be undefined:
“`jsx
app.post(‘/addpost’, (req, res) => {
const title = req.body.title;
const subject = req.body.subject;
const id = req.body.id;
if (id === ” || id === undefined) {
post.addPost(title, subject, (result) => {
res.send(result);
});
} else {
post.updatePost(id, title, subject, (result) => {
res.send(result);
});
}
});
“`
In `post.js`, create an `updatePost` method to update the blog post details:
“`jsx
updatePost(id, title, subject, callback) {
MongoClient.connect(URL, (err, db) => {
db.collection(‘post’).updateOne(
{ “_id”: new MongoDB.ObjectID(id) },
{ $set: { “title”: title, “subject”: subject } },
(err, result) => {
assert.equal(err, null);
if (err === null) {
callback(true);
} else {
callback(false);
}
}
);
});
}
“`
### Deleting Blog Posts
Add a click event to the delete icon:
“`jsx
this.deletePost(post._id)} className=”glyphicon glyphicon-trash”>
“`
In the `ShowPost` component, create a `deletePost` method:
“`jsx
deletePost(id) {
if (confirm(‘Are you sure?’)) {
// DELETE POST API call will go here!!
}
}
“`
Bind this method in the constructor and modify the mapping function callback:
“`jsx
constructor(props) {
super(props);
this.deletePost = this.deletePost.bind(this);
}
// …
this.state.posts.map((post, index) => (
// …
this.deletePost(post._id)} className=”glyphicon glyphicon-trash”>
).bind(this))
“`
Call the `getPost` method after deleting a post to refresh the blog post list. Create a `getPost` method and move the `componentDidMount` code to it:
“`jsx
getPost() {
axios.post(‘/getpost’, {}).then((response) => {
console.log(‘RES is’, response);
this.setState({ posts: response.data });
}).catch((error) => {
console.log(‘Error is’, error);
});
}
componentDidMount() {
this.getPost();
document.getElementById(‘homeHyperlink’).className = ‘active’;
document.getElementById(‘addHyperlink’).className = ”;
}
“`
Update the `deletePost` method to include the AJAX call to the `deletePost` API:
“`jsx
deletePost(id) {
if (confirm(‘Are you sure?’)) {
axios.post(‘/deletepost’, { id }).then((response) => {
this.getPost();
}).catch((error) => {
console.log(‘Error is’, error);
});
}
}
“`
In `app.js`, add the `deletePost` API:
“`jsx
app.post(‘/deletepost’, (req, res) => {
const id = req.body.id;
post.deletePost(id, (result) => {
res.send(result);
});
});
“`
In `post.js`, create the `deletePost` method to delete the entry from MongoDB:
“`jsx
deletePost(id, callback) {
MongoClient.connect(URL, (err, db) => {
db.collection(‘post’).deleteOne(
{ “_id”: new MongoDB.ObjectID(id) },
(err, result) => {
console.log(“Deleted post.”);
assert.equal(err, null);
if (err === null) {
callback(true);
} else {
callback(false);
}
}
);
});
}
“`
After saving these changes and restarting the server, try adding a new blog post and deleting it from the grid list. A confirmation message will appear before deletion. After confirming, the list will be updated accordingly.
### Conclusion
In this tutorial, you’ve learned how to update and delete blog posts in a React application. In the next part of this series, you’ll explore creating a profile page for logged-in users. Share your thoughts and suggestions in the comments below, and find the source code for this tutorial on GitHub.