In the previous part of this tutorial series, you learned how to implement the add and display post functionality. In this part of the tutorial series on creating a blog application in React, you will implement functionality to update and delete blog posts.
start using
Let's start by cloning the source code for the final part of this series.
https://github.com/royagasthyan/ReactBlogApp-AddPost
After cloning the directory, navigate to the project directory and install the required dependencies.
cd ReactBlogApp-AddPost npm install
Start the Node.js server and the application will run at http://localhost:7777/index.html#/.
Create update and delete views
Let’s modify the list of blog posts to display the data in a table with update and delete icons. In the render method of the ShowPost
component, replace the existing div
with the table, as shown in the code:
<table className="table table-striped"> <thead> <tr> <th>#</th> <th>Title</th> <th>Subject</th> <th></th> <th></th> </tr> </thead> <tbody> { this.state.posts.map(function(post,index) { return <tr key={index} > <td>{index+1}</td> <td>{post.title}</td> <td>{post.subject}</td> <td> <span className="glyphicon glyphicon-pencil"></span> </td> <td> <span className="glyphicon glyphicon-remove"></span> </td> </tr> }.bind(this)) } </tbody> </table>
As shown in the code above, you have modified the existing code to display the posts in a table format. You 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 see a list of blog posts in tabular format.
Implement update release function
To implement update publishing functionality, you need to attach a click event to the edit icon. Modify the edit icon span
as shown:
<span onClick={this.updatePost.bind(this,post._id)} className="glyphicon glyphicon-pencil"></span>
As shown in the code above, 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 shown in the code above, you have triggered a redirect to the add post page using the ID of the edited item. In the add post page you will get the details of the blog post with the passed ID and populate the details.
Modify the router to include the optional id parameter in the add post page.
<Route component={AddPost} path="/addPost(/:id)"></Route>
Inside the AddPost
component, create a method called getPostWithId
to get the blog post details using the id
. Within the getPostWithId
method, make an AJAX call to the getPostWithId
API within 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); }); }
You have updated the state variables title
and subject
with the response received from the getPostWithId
API method.
Modify the title
and subject
text boxes to display the value of the status variable.
<div className="form-group"> <input value={this.state.title} type="text" onChange={this.handleTitleChange} className="form-control" id="title" name="title" placeholder="Title" required /> </div> <div className="form-group"> <textarea value={this.state.subject} className="form-control" onChange={this.handleSubjectChange} type="textarea" id="subject" placeholder="Subject" maxlength="140" rows="7"></textarea> </div>
Now, let us create the getPostWithId
API in app.js
to make a database call to the MongoDB database to get the post details with a specific ID. This is the getPostWithId
API method:
app.post('/getPostWithId', function(req,res){ var id = req.body.id; post.getPostWithId(id, function(result){ res.send(result) }) })
In the post.js
file, create a method getPostWithId
to query the database for details. Its appearance is as follows:
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 shown in the code above, you used the findOne
API to get the details of a blog post with a specific 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 need to check the id
addPost
in app.js
within API methods. If this is a new post, id
will be undefined
.
Modify the AddPost
method in the AddPost
component to include the id
state variable.
axios.post('/addPost', { title: this.state.title, subject: this.state.subject, id: this.state.id })
In the addPost
API method, you need to check if the id
parameter is undefined
. If undefined
, it means this is a new post, otherwise the update method needs to be called. addPost
The API method is as follows:
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); }); } })
In the post.js
file, create a method named updatePost
to update the blog post details. You will utilize the updateOne
API to update the details of a blog post with a specific id
. Here's what the updatePost
method looks like:
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) } }); }); }
保存以上更改并重新启动服务器。登录应用程序并点击编辑图标。修改现有值并单击按钮更新详细信息。
实现删除帖子功能
要实现删除帖子功能,您需要将点击事件附加到删除图标。修改删除图标跨度如图:
<span onClick={this.deletePost.bind(this,post._id)} className="glyphicon glyphicon-remove"></span>
如上面的代码所示,您已将帖子 ID 作为参数传递给 deletePost
方法。
在 ShowPost
组件中创建一个名为 deletePost
的方法。
deletePost(id){ }
在ShowPost
组件构造函数中绑定该方法。
this.deletePost = this.deletePost.bind(this);
要在 map
函数回调中使用 this
,您需要将 this
绑定到 map
函数。修改map
函数回调如图:
{ this.state.posts.map(function(post,index) { return}.bind(this)) } {index+1} {post.title} {post.subject} <span onClick={this.updatePost.bind(this,post._id)} className="glyphicon glyphicon-pencil"></span> <span onClick={this.deletePost.bind(this,post._id)} className="glyphicon glyphicon-remove"></span>
在 deletePost
方法中,在调用删除 API 之前添加确认提示。
deletePost(id){ if(confirm('Are you sure ?')){ // Delete Post API call will be here !! } }
现在让我们在 app.js
文件中添加 deletePost
API。 API 将从 AJAX 调用中读取帖子 ID 并从 MongoDB 中删除该条目。以下是 deletePost
API 的外观:
app.post('/deletePost', function(req,res){ var id = req.body.id; post.deletePost(id, function(result){ res.send(result) }) })
如上面的代码所示,您将调用 post.js
文件中的 deletePost
方法并返回结果。让我们在 post.js
文件中创建 deletePost
方法。
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) } }); }) }
如上面的代码所示,post.js
文件中的 deletePost
方法将使用 MongoClient
连接到MongoDB 中的博客数据库。使用从 AJAX 调用传递的 Id
,它将从数据库中删除该帖子。
更新 home.jsx
文件中 deletePost
方法内的代码,以包含对 deletePost
API 的 AJAX 调用 app.js
文件。
deletePost(id){ if(confirm('Are you sure ?')){ var self = this; axios.post('/deletePost', { id: id }) .then(function (response) { }) .catch(function (error) { }); } }
删除博客文章后,您需要刷新博客文章列表以反映这一点。因此,创建一个名为 getPost
的新方法,并将 componentDidMount
代码移到该函数内。这是 getPost
方法:
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); }); }
修改componentDidMount
代码,如图:
componentDidMount(){ this.getPost(); document.getElementById('homeHyperlink').className = "active"; document.getElementById('addHyperLink').className = ""; }
在 deletePost
AJAX 调用成功回调内,调用 getPost
方法来更新博客文章列表。
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); }); } }
保存以上更改并重新启动服务器。尝试添加新的博客文章,然后从网格列表中单击“删除”。系统将提示您一条删除确认消息。单击确定按钮后,该条目将被删除,并且博客文章列表将被更新。
总结
在本教程中,您了解了如何在 React 博客应用程序中实现删除和更新博客文章功能。在本教程系列的下一部分中,您将了解如何为登录用户实现个人资料页面。
请在下面的评论中告诉我们您的想法和建议。本教程的源代码可在 GitHub 上获取。
The above is the detailed content of Updating and deleting posts in a React-based blog application: Part 4. For more information, please follow other related articles on the PHP Chinese website!

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

WordPress is very customized, providing a wide range of flexibility and customizability. 1) Through the theme and plug-in ecosystem, 2) use RESTAPI for front-end development, 3) In-depth code level modifications, users can achieve a highly personalized experience. However, customization requires mastering technologies such as PHP, JavaScript, CSS, etc., and pay attention to performance optimization and plug-in selection to avoid potential problems.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
