In the previous part of this tutorial series, you saw how to implement the add and display post functionality. In this part of the tutorial series on creating a blogging app in React, you’ll implement the functionality to update and delete the blog posts.
Getting Started
Let’s get started by cloning the source code from the last part of the series.
https://github.com/royagasthyan/ReactBlogApp-AddPost
Once the directory has been cloned, navigate to the project directory and install the required dependencies.
cd ReactBlogApp-AddPost npm install
Start the Node.js server and you will have the application running at http://localhost:7777/index.html#/.
Creating the Update and Delete View
Let’s modify the blog post listing to display the data in a tabular form with the update and delete icons. Inside the render method of the ShowPost
component, replace the existing div
with a table as shown in the code:
# | Title | Subject | ||
---|---|---|---|---|
{index+1} | {post.title} | {post.subject} |
As seen in the above code, you have modified the existing code to display the posts in a tabular form. You have mapped the posts
variable to iterate over the posts collection and dynamically create the required tr
and td
.
Save the above changes and restart the server. Point your browser to http://localhost:7777/home#/ and you should be able to view the blog post listing in tabular format.
Implementing the Update Post Function
To implement the update post functionality, you need to attach the on-click event to the edit icon. Modify the edit icon span
as shown:
As seen in the above code, you have passed the post id as a parameter to the updatePost
method.
Create a method updatePost
inside the ShowPost
component.
updatePost(id){ hashHistory.push('/addPost/' + id); }
As seen in the above code, you have triggered the redirect to the add post page with the id of the edited item. In the add post page, you’ll get the details of the blog post with the passed id and populate the details.
Modify the router to include an optional id parameter to the add post page.
Inside the AddPost
component, create a method called getPostWithId
to fetch the details of the blog post with id
. Inside the getPostWithId
method, make an AJAX call to the getPostWithId
API inside app.js
.
getPostWithId(){ var id = this.props.params.id; var self = this; axios.post('/getPostWithId', { id: id }) .then(function (response) { if(response){ self.setState({title:response.data.title}); self.setState({subject:response.data.subject}); } }) .catch(function (error) { console.log('error is ',error); }); }
With the response received from the getPostWithId
API method, you have updated the state variables title
and subject
.
Modify the title
and subject
text boxes to display the value from the state variables.
Now let’s create the getPostWithId
API inside app.js
to make a database call to the MongoDB database to get the post details with a particular Id. Here is the getPostWithId
API method:
app.post('/getPostWithId', function(req,res){ var id = req.body.id; post.getPostWithId(id, function(result){ res.send(result) }) })
Inside the post.js
file, create a method getPostWithId
to query the database to fetch the details. Here is how it looks:
getPostWithId: function(id, callback){ MongoClient.connect(url, function(err, db){ db.collection('post').findOne({ _id: new mongodb.ObjectID(id) }, function(err, result){ assert.equal(err, null); if(err == null){ callback(result) } else{ callback(false) } }); }) }
As seen in the above code, you have made use of the findOne
API to get the details of the blog post with a particular Id.
Save the above changes and try to run the program. Click the edit icon on the home page and it will redirect to the add post page and populate the title and subject.
Now, to update the blog post details, you’ll need to check for the id
inside the addPost
API method in the app.js
. If it’s a new post, the id
will be undefined
.
Modify the addPost
method inside the AddPost
component to include the id
state variable.
axios.post('/addPost', { title: this.state.title, subject: this.state.subject, id: this.state.id })
Inside the addPost
API method, you need to check if the id
parameter is undefined
or not. If undefined
, it means it’s a new post, else you need to call the update method. Here is what the addPost
API method looks like:
app.post('/addpost', function (req, res) { var title = req.body.title; var subject = req.body.subject; var id = req.body.id; if(id == '' || id == undefined) post.addPost(title, subject ,function(result){ res.send(result); }); } else{ post.updatePost(id, title, subject ,function(result){ res.send(result); }); } })
Inside the post.js
file, create a method called updatePost
to update the blog post details. You’ll make use of the updateOne
API to update the details of the blog post with the particular id
. Here is how the updatePost
method looks:
updatePost: function(id, title, subject, callback){ MongoClient.connect(url, function(err, db) { db.collection('post').updateOne( { "_id": new mongodb.ObjectID(id) }, { $set: { "title" : title, "subject" : subject } },function(err, result){ assert.equal(err, null); if(err == null){ callback(true) } else{ callback(false) } }); }); }
Save the above changes and restart the server. Log in to the application and click on the edit icon. Modify the existing values and click the button to update the details.
Implementing the Delete Post Function
To implement the delete post functionality, you need to attach the on-click event to the delete icon. Modify the delete icon span as shown:
As seen in the above code, you have passed the post id as a parameter to the deletePost
method.
Create a method called deletePost
inside the ShowPost
component.
deletePost(id){ }
Bind the method in the ShowPost
component constructor.
this.deletePost = this.deletePost.bind(this);
For using this
inside the map
function callback, you need to bind this
to the map
function. Modify the map
function callback as shown:
{ this.state.posts.map(function(post,index) { return}.bind(this)) } {index+1} {post.title} {post.subject}
Inside the deletePost
method, add a confirmation prompt before calling the delete API.
deletePost(id){ if(confirm('Are you sure ?')){ // Delete Post API call will be here !! } }
Now let’s add the deletePost
API inside the app.js
file. The API will read the post Id from the AJAX call and delete the entry from MongoDB. Here is how the deletePost
API looks:
app.post('/deletePost', function(req,res){ var id = req.body.id; post.deletePost(id, function(result){ res.send(result) }) })
As seen in the above code, you will make a call to the deletePost
method in the post.js
file and return the result. Let’s create the deletePost
method inside the post.js
file.
deletePost: function(id, callback){ MongoClient.connect(url, function(err, db){ db.collection('post').deleteOne({ _id: new mongodb.ObjectID(id) }, function(err, result){ assert.equal(err, null); console.log("Deleted the post."); if(err == null){ callback(true) } else{ callback(false) } }); }) }
As seen in the above code, the deletePost
method in the post.js
file will make use of the MongoClient
to connect to the blog database in MongoDB. Using the Id
passed from the AJAX call, it will delete the post from the database.
Update the code inside the deletePost
method in the home.jsx
file to include the AJAX call to the deletePost
API in the app.js
file.
deletePost(id){ if(confirm('Are you sure ?')){ var self = this; axios.post('/deletePost', { id: id }) .then(function (response) { }) .catch(function (error) { }); } }
Once the blog post has been deleted, you need to refresh the blog post listing to reflect this. So create a new method called getPost
and move the componentDidMount
code inside that function. Here is the getPost
method:
getPost(){ var self = this; axios.post('/getPost', { }) .then(function (response) { console.log('res is ',response); self.setState({posts:response.data}) }) .catch(function (error) { console.log('error is ',error); }); }
Modify the componentDidMount
code as shown:
componentDidMount(){ this.getPost(); document.getElementById('homeHyperlink').className = "active"; document.getElementById('addHyperLink').className = ""; }
Inside the deletePost
AJAX call success callback, make a call to the getPost
method to update the blog post listing.
deletePost(id){ if(confirm('Are you sure ?')){ var self = this; axios.post('/deletePost', { id: id }) .then(function (response) { self.getPost(); }) .catch(function (error) { console.log('Error is ',error); }); } }
Save the above changes and restart the server. Try adding a new blog post, and then click delete from the grid list. You will be prompted with a delete confirmation message. Once you click the OK button, the entry will be deleted and the blog post listing will be updated.
Wrapping It Up
In this tutorial, you saw how to implement the delete and update blog post functionality in the React blog application. In the next part of the tutorial series, you’ll learn how to implement the profile page for a logged-in user.
Do let us know your thoughts and suggestions in the comments below. Source code from this tutorial is available on GitHub.