1. Code
  2. JavaScript
  3. React

Creating a Blogging App Using React, Part 4: Update & Delete Posts

Scroll to top
7 min read
This post is part of a series called Creating a Blogging App Using React.
Creating a Blogging App Using React, Part 3: Add & Display Posts
Creating a Blogging App Using React, Part 5: Profile Page

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.

1
https://github.com/royagasthyan/ReactBlogApp-AddPost

Once the directory has been cloned, navigate to the project directory and install the required dependencies.

1
cd ReactBlogApp-AddPost
2
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:

1
<table className="table table-striped">
2
            <thead>
3
              <tr>
4
                <th>#</th>

5
                <th>Title</th>

6
                <th>Subject</th>

7
                <th></th>

8
                <th></th>

9
              </tr>

10
            </thead>

11
            <tbody>
12
              {
13
                this.state.posts.map(function(post,index) {
14
                   return <tr key={index} >
15
                            <td>{index+1}</td>

16
                            <td>{post.title}</td>

17
                            <td>{post.subject}</td>

18
                            <td>
19
                              <span className="glyphicon glyphicon-pencil"></span>

20
                            </td>

21
                            <td>
22
                              <span className="glyphicon glyphicon-remove"></span>

23
                            </td>

24
                          </tr>

25
                }.bind(this))
26
              }
27
            </tbody>

28
</table>

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.

Blog Post Listing With Update  DeleteBlog Post Listing With Update  DeleteBlog Post Listing With Update  Delete

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: 

1
<span onClick={this.updatePost.bind(this,post._id)} className="glyphicon glyphicon-pencil"></span>

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.

1
updatePost(id){
2
  hashHistory.push('/addPost/' + id);
3
}

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.

1
<Route component={AddPost} path="/addPost(/:id)"></Route>

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.

1
getPostWithId(){
2
  var id = this.props.params.id;
3
  var self = this;
4
  axios.post('/getPostWithId', {
5
    id: id
6
  })
7
  .then(function (response) {
8
    if(response){
9
      self.setState({title:response.data.title});
10
      self.setState({subject:response.data.subject});  
11
    }
12
  })
13
  .catch(function (error) {
14
    console.log('error is ',error);
15
  });
16
}

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.

1
<div className="form-group">
2
    <input value={this.state.title} type="text" onChange={this.handleTitleChange} className="form-control" id="title" name="title" placeholder="Title" required />
3
</div>
4
               
5
<div className="form-group">
6
    <textarea value={this.state.subject} className="form-control" onChange={this.handleSubjectChange} type="textarea" id="subject" placeholder="Subject" maxlength="140" rows="7"></textarea>
7
</div>

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:

1
app.post('/getPostWithId', function(req,res){
2
  var id = req.body.id;
3
  post.getPostWithId(id, function(result){
4
    res.send(result)
5
  })
6
})

Inside the post.js file, create a method getPostWithId to query the database to fetch the details. Here is how it looks:

1
getPostWithId: function(id, callback){
2
	MongoClient.connect(url, function(err, db){
3
		 db.collection('post').findOne({
4
		 	_id: new mongodb.ObjectID(id)
5
		 },
6
		 function(err, result){
7
			assert.equal(err, null);
8
	    	if(err == null){
9
	    		callback(result)
10
	    	}
11
	    	else{
12
	    		callback(false)
13
	    	}
14
		});
15
	})
16
}

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.

React Blog App Edit ScreenReact Blog App Edit ScreenReact Blog App Edit Screen

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.

1
axios.post('/addPost', {
2
    title: this.state.title,
3
    subject: this.state.subject,
4
    id: this.state.id
5
})

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:

1
app.post('/addpost', function (req, res) {
2
  var title = req.body.title;
3
  var subject = req.body.subject;
4
  var id = req.body.id;
5
  if(id == '' || id == undefined)
6
    post.addPost(title, subject ,function(result){
7
      res.send(result);
8
    }); 
9
  }
10
  else{
11
    post.updatePost(id, title, subject ,function(result){
12
      res.send(result);
13
    }); 
14
  }
15
})

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:

1
updatePost: function(id, title, subject, callback){
2
	MongoClient.connect(url, function(err, db) {
3
	  	db.collection('post').updateOne( 
4
	  		{ "_id": new mongodb.ObjectID(id) },
5
	  		{ $set: 
6
	  			{ "title" : title,
7
	  			  "subject" : subject 
8
	  			}
9
	  		},function(err, result){
10
			assert.equal(err, null);
11
	    	if(err == null){
12
	    		callback(true)
13
	    	}
14
	    	else{
15
	    		callback(false)
16
	    	}
17
		});
18
	});
19
}

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:

1
<span onClick={this.deletePost.bind(this,post._id)} className="glyphicon glyphicon-remove"></span>

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.

1
deletePost(id){
2
      
3
}

Bind the method in the ShowPost component constructor.

1
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:

1
<tbody>
2
      {
3
        this.state.posts.map(function(post,index) {
4
           return <tr key={index} >
5
                    <td>{index+1}</td>
6
                    <td>{post.title}</td>
7
                    <td>{post.subject}</td>
8
                    <td>
9
                      <span onClick={this.updatePost.bind(this,post._id)} className="glyphicon glyphicon-pencil"></span>
10
                    </td>
11
                    <td>
12
                      <span onClick={this.deletePost.bind(this,post._id)} className="glyphicon glyphicon-remove"></span>
13
                    </td>
14
                  </tr>
15
        }.bind(this))
16
      }
17
 </tbody>

Inside the deletePost method, add a confirmation prompt before calling the delete API.

1
deletePost(id){
2
  if(confirm('Are you sure ?')){
3
    // Delete Post API call will be here !!

4
  }
5
}

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:

1
app.post('/deletePost', function(req,res){
2
  var id = req.body.id;
3
  post.deletePost(id, function(result){
4
    res.send(result)
5
  })
6
})

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.

1
deletePost: function(id, callback){
2
3
	MongoClient.connect(url, function(err, db){
4
		 db.collection('post').deleteOne({
5
		 	_id: new mongodb.ObjectID(id)
6
		 },
7
		 function(err, result){
8
			assert.equal(err, null);
9
	    	console.log("Deleted the post.");
10
	    	if(err == null){
11
	    		callback(true)
12
	    	}
13
	    	else{
14
	    		callback(false)
15
	    	}
16
		});
17
	})
18
}

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.

1
deletePost(id){
2
  if(confirm('Are you sure ?')){
3
    var self = this;
4
    axios.post('/deletePost', {
5
      id: id
6
    })
7
    .then(function (response) {
8
      
9
    })
10
    .catch(function (error) {
11
      
12
    });
13
  }
14
}

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:

1
getPost(){
2
  var self = this;
3
  axios.post('/getPost', {
4
  })
5
  .then(function (response) {
6
    console.log('res is ',response);
7
    self.setState({posts:response.data})
8
  })
9
  .catch(function (error) {
10
    console.log('error is ',error);
11
  });
12
}

Modify the componentDidMount code as shown:

1
componentDidMount(){
2
  this.getPost();
3
4
  document.getElementById('homeHyperlink').className = "active";
5
  document.getElementById('addHyperLink').className = "";
6
}

Inside the deletePost AJAX call success callback, make a call to the getPost method to update the blog post listing.

1
deletePost(id){
2
  if(confirm('Are you sure ?')){
3
    var self = this;
4
    axios.post('/deletePost', {
5
      id: id
6
    })
7
    .then(function (response) {
8
      self.getPost();
9
    })
10
    .catch(function (error) {
11
      console.log('Error is ',error);
12
    });
13
  }
14
}

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.

Delete Blog Post ConfirmationDelete Blog Post ConfirmationDelete Blog Post Confirmation

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.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.