<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by MI Shajib on Medium]]></title>
        <description><![CDATA[Stories by MI Shajib on Medium]]></description>
        <link>https://medium.com/@mishajib?source=rss-1afcb495f0f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1-aTXGXWxT7Hu9p9</url>
            <title>Stories by MI Shajib on Medium</title>
            <link>https://medium.com/@mishajib?source=rss-1afcb495f0f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:35:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mishajib/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MongoDB Replica Set: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@mishajib/mongodb-replica-set-a-step-by-step-guide-f169d552bfb8?source=rss-1afcb495f0f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f169d552bfb8</guid>
            <category><![CDATA[replication]]></category>
            <category><![CDATA[mongodb-replica-set]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[replicaset]]></category>
            <dc:creator><![CDATA[MI Shajib]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 18:27:02 GMT</pubDate>
            <atom:updated>2024-11-25T18:27:02.234Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>MongoDB</strong> <strong>replica sets</strong> are a key feature for ensuring high availability and redundancy in your database setup. In this article, we’ll walk you through what a replica set is, its advantages, and how to set it up with and without a configuration file.</p><h3>What is a Replica Set in MongoDB?</h3><p>A <strong>replica set</strong> is a group of MongoDB servers that maintain the same data set. In a replica set:</p><ul><li><strong>Primary Node</strong>: Handles all write operations.</li><li><strong>Secondary Nodes</strong>: Maintain copies of the primary’s data and handle read operations if configured.</li><li><strong>Arbiter Node (optional)</strong>: Participates in elections but does not store data. It participates in voting to choose the node if one node is down.</li></ul><p>If the primary node goes down, one of the secondary nodes is promoted to primary, ensuring your application remains available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*-uKYPhZUU3W9_IlL_w_P5Q.png" /></figure><h3>Advantages of Replica Sets</h3><ol><li><strong>High Availability</strong>: Ensures database uptime even during failures.</li><li><strong>Data Redundancy</strong>: Protects against data loss.</li><li><strong>Improved Read Scalability</strong>: Secondary nodes can handle read queries.</li><li><strong>Automatic Failover</strong>: Promotes a secondary to primary automatically.</li></ol><h3>Setting Up MongoDB Replica Set</h3><p>You can set up a replica set in two ways:</p><ol><li><strong>Without a Configuration File</strong> (using command-line arguments).</li><li><strong>With a Configuration File</strong> (recommended for production).</li></ol><h3>Example 1: Setting Up a Replica Set</h3><h4>Step 1: Start Multiple MongoDB Instances</h4><p>You need to run at least three MongoDB instances for a replica set. Open three terminal windows and run the following commands:</p><p><strong>Node 1 (Primary):</strong></p><pre>mongod --replSet rs0 --dbpath /data/db1 --logpath /data/db1/mongodb.log --port 27017 --fork</pre><p><strong>Node 2 (Secondary):</strong></p><pre>mongod --replSet rs0 --dbpath /data/db2 --logpath /data/db2/mongodb.log --port 27018 --fork</pre><p><strong>Node 3 (Secondary or Arbiter):</strong></p><pre>mongod --replSet rs0 --dbpath /data/db3 --logpath /data/db3/mongodb.log --port 27019 --fork</pre><h4>Step 2: Connect to the Primary Instance</h4><p>Open another terminal and connect to the MongoDB shell on the primary node:</p><pre>mongosh --port 27017</pre><h4>Step 3: Initiate the Replica Set</h4><p>In the MongoDB shell, run the following command to initialize the replica set:</p><pre>rs.initiate({<br>  _id: &quot;rs0&quot;,<br>  members: [<br>    { _id: 0, host: &quot;localhost:27017&quot; },<br>    { _id: 1, host: &quot;localhost:27018&quot; },<br>    { _id: 2, host: &quot;localhost:27019&quot; }<br>  ]<br>})</pre><h4>Step 4: Check Replica Set Status</h4><p>Verify the replica set status:</p><pre>rs.status()</pre><p>You should see information about the primary and secondary nodes.</p><h3>Conclusion</h3><p>Setting up a MongoDB replica set ensures that your database is highly available and scalable. Whether you choose to configure it manually via the shell or use configuration files, the process is straightforward. By implementing a replica set, you safeguard your data against server failures and improve your application’s reliability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f169d552bfb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB CRUD Operations: A Beginner’s Guide]]></title>
            <link>https://medium.com/@mishajib/mongodb-crud-operations-a-beginners-guide-433c3621a076?source=rss-1afcb495f0f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/433c3621a076</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb-atlas]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[mongodb-tutorial]]></category>
            <dc:creator><![CDATA[MI Shajib]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 13:07:33 GMT</pubDate>
            <atom:updated>2024-11-09T13:07:33.453Z</atom:updated>
            <content:encoded><![CDATA[<p>MongoDB, a popular NoSQL database, allows for dynamic, schema-less data storage, making it a great fit for modern web applications. In this guide, we’ll dive into the core CRUD (Create, Read, Update, Delete) operations in MongoDB and explore how to perform them using the MongoDB shell and Node.js.</p><h3>Prerequisites</h3><p>To follow along, ensure you have:</p><ol><li>MongoDB is installed on your system.</li><li>MongoDB Compass or access to the MongoDB shell (for CLI examples).</li><li>Basic knowledge of JavaScript if you’re using Node.js.</li></ol><p>Let’s get started!</p><h3>1. Setting Up MongoDB</h3><p>If you haven’t installed MongoDB, follow the <a href="https://docs.mongodb.com/manual/installation/">official installation guide</a>. Once MongoDB is up and running, connect to the database:</p><pre>mongosh</pre><p>This command opens the MongoDB shell, allowing you to interact with your databases.</p><h3>2. The Basics of CRUD</h3><p>CRUD operations allow you to manage data within MongoDB collections. Here’s a breakdown of what each operation does:</p><ul><li><strong>Create</strong> — Insert new data into the collection.</li><li><strong>Read</strong> — Retrieve data from the collection.</li><li><strong>Update</strong> — Modify existing data.</li><li><strong>Delete</strong> — Remove data from the collection.</li></ul><p>Now, let’s look at how to perform these operations.</p><h3>3. Create Operation</h3><p>To add new documents to a MongoDB collection, use the insertOne or insertMany methods.</p><h4>Example</h4><p>Let’s create a database called blogDB and a collection named posts:</p><pre>use blogDB</pre><pre>db.posts.insertOne({<br>  title: &quot;Introduction to MongoDB&quot;,<br>  author: &quot;Jane Doe&quot;,<br>  content: &quot;This is a guide on MongoDB CRUD operations.&quot;,<br>  tags: [&quot;MongoDB&quot;, &quot;Database&quot;, &quot;CRUD&quot;],<br>  published: true,<br>  views: 150<br>})</pre><p>Here, insertOne inserts a single document into the posts collection.</p><p>To insert multiple documents, use insertMany:</p><pre>db.posts.insertMany([<br>  { title: &quot;Post 1&quot;, author: &quot;John Smith&quot;, views: 120 },<br>  { title: &quot;Post 2&quot;, author: &quot;Mary Jane&quot;, views: 180 }<br>])</pre><h3>4. Read Operation</h3><p>Reading data from MongoDB allows you to retrieve documents that match specific criteria.</p><h4>Find All Documents</h4><pre>db.posts.find()</pre><p>This command retrieves all documents from the posts collection.</p><h4>Filter Documents</h4><p>To filter documents, provide a query object. For example, to find posts by a specific author:</p><pre>db.posts.find({ author: &quot;Jane Doe&quot; })</pre><p>Use findOne to get the first matching document:</p><pre>db.posts.findOne({ title: &quot;Introduction to MongoDB&quot; })</pre><h4>Advanced Querying</h4><p>MongoDB supports advanced querying options such as range operators. For instance, to find posts with more than 100 views:</p><pre>db.posts.find({ views: { $gt: 100 } })</pre><h3>5. Update Operation</h3><p>Updating documents allows you to modify existing data. Use updateOne or updateMany for partial updates, and replaceOne for replacing a document entirely.</p><h4>Update a Single Document</h4><p>To update a single document, use updateOne:</p><pre>db.posts.updateOne(<br>  { title: &quot;Introduction to MongoDB&quot; },<br>  { $set: { views: 200 } }<br>)</pre><p>Here, $set is an update operator that modifies the views field.</p><h4>Update Multiple Documents</h4><p>To update multiple documents, use updateMany:</p><pre>db.posts.updateMany(<br>  { author: &quot;Jane Doe&quot; },<br>  { $set: { published: false } }<br>)</pre><p>This query sets the published status to false for all posts by &quot;Jane Doe&quot;.</p><h3>6. Delete Operation</h3><p>Deleting documents removes them from the collection.</p><h4>Delete a Single Document</h4><p>To delete a single document, use deleteOne:</p><pre>db.posts.deleteOne({ title: &quot;Introduction to MongoDB&quot; })</pre><h4>Delete Multiple Documents</h4><p>To delete multiple documents, use deleteMany:</p><pre>db.posts.deleteMany({ author: &quot;John Smith&quot; })</pre><h3>Bonus: Using MongoDB CRUD Operations with Node.js</h3><p>Now, let’s see how these operations look in Node.js using the official MongoDB Node.js driver.</p><h4>Setting Up the Environment</h4><ol><li>Initialize a new Node.js project and install the MongoDB driver:</li></ol><pre>npm init -y<br>npm install mongodb</pre><p>2. Connect to MongoDB and perform operations:</p><pre>const { MongoClient } = require(&quot;mongodb&quot;);<br><br>async function main() {<br>  const uri = &quot;mongodb://localhost:27017&quot;;<br>  const client = new MongoClient(uri);<br><br>  try {<br>    await client.connect();<br>    const db = client.db(&quot;blogDB&quot;);<br>    const posts = db.collection(&quot;posts&quot;);<br><br>    // Create<br>    await posts.insertOne({ title: &quot;New Post&quot;, views: 100 });<br><br>    // Read<br>    const post = await posts.findOne({ title: &quot;New Post&quot; });<br>    console.log(post);<br><br>    // Update<br>    await posts.updateOne({ title: &quot;New Post&quot; }, { $set: { views: 200 } });<br><br>    // Delete<br>    await posts.deleteOne({ title: &quot;New Post&quot; });<br>  } finally {<br>    await client.close();<br>  }<br>}<br><br>main().catch(console.error);</pre><h3>Conclusion</h3><p>Understanding these CRUD operations is fundamental for working with MongoDB. Whether you’re working directly in the MongoDB shell or building applications with Node.js, MongoDB’s flexible schema and powerful querying capabilities make it a versatile choice for storing and managing data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=433c3621a076" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connect network namespaces through veth (virtual ethernet) cable]]></title>
            <link>https://medium.com/@mishajib/connect-network-namespaces-through-veth-virtual-ethernet-cable-fb1d3a2a40f7?source=rss-1afcb495f0f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb1d3a2a40f7</guid>
            <category><![CDATA[network-namespace]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[linux-namespace]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[MI Shajib]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 09:51:08 GMT</pubDate>
            <atom:updated>2023-06-17T09:51:08.093Z</atom:updated>
            <content:encoded><![CDATA[<p>Repository Link:- <a href="https://github.com/mishajib/network-namespace">https://github.com/mishajib/network-namespace</a></p><p>If you want to create a small project like this quickly with Python, Nodejs, and Shell Scripts then you can check this repository.</p><p>In this medium article, I will show what is network namespaces, and how to connect them by <strong>veth(virtual ethernet)</strong> cable. In this article, I’m using the <strong>Ubuntu OS</strong> command.</p><p>So let’s get started — —</p><p>First, we need to know what is network namespace and how to work network namespaces. And then we move forward to the coding/practical overview.</p><h3>What is Network namespace and How to work network namespace?</h3><p>Network namespaces are a Linux kernel feature allowing us to isolate network environments through virtualization. It’s actually called <strong>Linux Network Namespace.</strong></p><p>For example, using network namespaces, you can create separate network interfaces and routing tables that are isolated from the rest of the system and operate independently.</p><p>One real-life example is where network namespaces are commonly used in containerization technology, such as <strong>Docker</strong> or <strong>Kubernetes</strong>. Containers provide lightweight, isolated environments for running applications, and network namespaces play a crucial role in enabling network isolation and connectivity for these containers.</p><p>Now let’s try to create network namespaces and connect them by <strong>veth(virtual ethernet)</strong> cable.</p><h3>Connect Network Namespaces by Veth(Virtual Ethernet) Cable</h3><h4>Step-1: Creating Network Namespaces</h4><p>Open a terminal and execute/run the following commands to create network namespaces.</p><pre>sudo ip netns add red<br>sudo ip netns add blue</pre><h4>Step-2: Configuring the Veth(Virtual Ethernet) Cable</h4><p>Create a <strong>veth(virtual ethernet)</strong> pair by executing the following command.</p><pre>sudo ip link add veth-red type veth peer name veth-blue</pre><p>Set <strong>veth(virtual ethernet)</strong> cable to each network namespace.</p><pre>sudo ip link set veth-red netns red<br>sudo ip link set veth-blue netns blue</pre><h4>Step-3: Configuring IP Addresses</h4><p>Assign IP addresses to the <strong>veth(virtual ethernet)</strong> interfaces within the respective namespaces.</p><pre>sudo ip -n red addr add 10.0.0.1/24 dev veth-red<br>sudo ip -n blue addr add 10.0.0.2/24 dev veth-blue</pre><p>or You can run the following commands also.</p><pre>sudo ip netns exec red ip addr add 10.0.0.1/24 dev veth-red<br>sudo ip netns exec blue ip addr add 10.0.0.2/24 dev veth-blue</pre><h4>Step-4: Enabling/bringing up/active veth interfaces/cables</h4><p>Execute/run the following commands to bring up <strong>veth(virtual ethernet)</strong> interfaces/cables.</p><pre>sudo ip -n blue link set veth-red up<br>sudo ip -n blue link set veth-blue up</pre><h4>Step-5: Testing connectivity</h4><p>Ping the IP address from one network namespace to another network namespace IP address, to check the connection is successful and check the packet is passing successfully from one to another network namespace.</p><pre>sudo ip netns exec red ping 10.0.0.2</pre><p>Output: If you see the like below then your connection is successful.</p><pre>PING 10.0.0.2 (10.0.0.2) 56(84) bytes of data.<br>64 bytes from 10.0.0.2: icmp_seq=1 ttl=64 time=0.023 ms<br>64 bytes from 10.0.0.2: icmp_seq=2 ttl=64 time=0.044 ms<br>64 bytes from 10.0.0.2: icmp_seq=3 ttl=64 time=0.049 ms<br>64 bytes from 10.0.0.2: icmp_seq=4 ttl=64 time=0.048 ms<br>64 bytes from 10.0.0.2: icmp_seq=5 ttl=64 time=0.050 ms<br>^C<br>--- 10.0.0.2 ping statistics ---<br>5 packets transmitted, 5 received, 0% packet loss, time 4081ms<br>rtt min/avg/max/mdev = 0.023/0.042/0.050/0.010 ms</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*upr_ogOPjdS4ko8NV-vyZA.png" /><figcaption>Network Namespace Connectivity With Veth(Virtual Ethernet) Cable</figcaption></figure><h3>Conclusion:</h3><p>By following the steps in this example, you can successfully connect two network namespaces using a veth(virtual ethernet) cable.</p><p>So, in this article, we learned about the network namespace and connect them by veth(virtual ethernet) cable.</p><p>I hope you find this article interesting and learned something new.</p><h4><strong>— — — — — — — — Thanks for reading this article — — — — — — — —</strong></h4><h3>— — — — — — — — Happy Coding — — — — — — — — —</h3><ul><li>You can connect with me on <a href="https://github.com/mishajib/">Github</a> and <a href="https://www.linkedin.com/in/mishajib/">Linkedin</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb1d3a2a40f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node (EXPRESS) and React CRUD App with — Redis, MySQL.]]></title>
            <link>https://medium.com/@mishajib/node-express-and-react-crud-app-with-redis-mysql-c21275a8211d?source=rss-1afcb495f0f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c21275a8211d</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[MI Shajib]]></dc:creator>
            <pubDate>Sat, 10 Jun 2023 11:18:40 GMT</pubDate>
            <atom:updated>2023-06-10T11:18:40.448Z</atom:updated>
            <content:encoded><![CDATA[<h3>Node (EXPRESS) and React CRUD App with — Redis, MySQL.</h3><p>Repository Link:- <a href="https://github.com/mishajib/node-express-react-todo-list">https://github.com/mishajib/node-express-react-todo-list</a></p><p>If you want to quickly set up then clone this repo and run.</p><p>In this medium article, I will show you how to perform basic CRUD operations with the help of Node.js(EXPRESS), React.js, MySQL, and Redis. You will also get an idea of project setup in Node(EXPRESS) and React.js.</p><h3>Features:</h3><ul><li><strong>CRUD</strong> (Create, Read, Update, Delete) with Node(Express) and React.</li><li>Use <strong>MySQL</strong> database to store data.</li><li>Caching by <strong>Redis</strong> for optimizing the query and fast data fetching.</li></ul><h3>Project Setup:</h3><h4>Node.js(Express.js) -&gt;</h4><h4>Step-1</h4><ul><li>To create a new project run the below command where you made your project directory.</li><li>It is used to set up a new or existing npm package.</li></ul><pre>npm init</pre><h4>Step-2</h4><ul><li>Now install the below packages.</li></ul><pre>npm install express cors nodemon mysql redis</pre><ul><li><strong>Express:</strong> Express.js is a free and open-source web application framework for Node.js. It is used for designing and building web applications quickly and easily.</li><li><strong>CORS:</strong> The <strong>CORS (Cross-Origin Resource Sharing)</strong> package is a package that can be used to handle cross-origin requests. Cross-origin requests are HTTP requests made from a different domain, protocol, or port than the one serving the webpage.</li><li><strong>Nodemon:</strong> <strong>Nodemon</strong> is a utility for Node.js applications that helps in development by automatically restarting the Node.js application whenever changes are detected in the source code.</li><li><strong>MySQL:</strong> <strong>MySQL</strong> is an open-source relational database management system (RDBMS) that is widely used for managing and storing structured data.</li><li><strong>Redis:</strong> <strong>Redis (Remote Dictionary Server)</strong> is an open-source, in-memory data structure store that can be used as a database, cache, or message broker. It is known for its exceptional performance, flexibility, and versatility. Redis is often referred to as a key-value store since it primarily stores data in key-value pairs. It is widely used in various applications for caching, real-time analytics, session management, pub/sub messaging, and more.</li></ul><h4>Step-3</h4><ul><li>In the package.json file, write the below command inside the scripts object. So, when you run the server using npm start it will run the index.js file using <strong>Nodemon</strong>.</li></ul><pre>&quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;nodemon index.js&quot;<br>}</pre><h4>Step-4</h4><ul><li>Run the server 😀</li></ul><pre>npm start</pre><h4>React.Js -&gt;</h4><h4>Step-1</h4><ul><li>To create a new project run the below command where you made your project directory.</li></ul><pre>npx create-react-app todo-app-frontend</pre><h4>Step-2</h4><ul><li>Now install the below packages.</li></ul><pre>npm install axios bootstrap</pre><ul><li><strong>Axios:</strong> <strong>Axios</strong> is a popular JavaScript library that is used to make HTTP requests from web browsers or Node.js applications. It provides a simple and elegant API for performing asynchronous HTTP requests, handling responses, and managing request and response interceptors.</li><li><strong>Bootstrap:</strong> <strong>Bootstrap</strong> is a popular open-source front-end framework that provides a collection of pre-built HTML, CSS, and JavaScript components and styles. It simplifies the process of creating responsive and mobile-first web pages and web applications, allowing developers to quickly prototype and build visually appealing and consistent user interfaces.</li></ul><h4>Step-3</h4><ul><li>Run the server 😀</li></ul><pre>npm start</pre><h3>The CRUD with Node(Express)</h3><p>Now, we will learn how to perform CRUD operations. CRUD stands for Create, Read, Update, and Delete.</p><h4>Setup Server</h4><ul><li>Create a index.js file in the root directory of the project. And also set up the application and server.</li></ul><pre>const cors    = require(&quot;cors&quot;);<br>const express = require(&quot;express&quot;);<br>const app     = express();<br>const mysql   = require(&#39;mysql&#39;);<br>const redis   = require(&#39;redis&#39;);<br><br>// Set up CORS<br>const corsOptions = {<br>    origin: &quot;http://localhost:3000&quot;<br>};<br>app.use(cors(corsOptions));<br>// Set json for getting data from request body<br>app.use(express.json());<br>// Redis setup<br>let redisClient;<br>(async () =&gt; {<br>    redisClient = redis.createClient();<br>    redisClient.on(&quot;error&quot;, (error) =&gt; console.error(`Error : ${error}`));<br>    redisClient.on(&quot;connect&quot;, () =&gt; console.log(&quot;Redis connected&quot;));<br>    await redisClient.connect();<br>})();<br>// MySQL setup<br>const DB = mysql.createConnection({<br>    host    : &#39;localhost&#39;,<br>    user    : &#39;root&#39;,<br>    password: &#39;toor&#39;,<br>    database: &#39;todo_list&#39;,<br>});<br>// Connect to MySQL<br>DB.connect((err) =&gt; {<br>    if (err) throw err;<br>    console.log(&#39;MySQL connected&#39;);<br>});<br>// Routes<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    res.send(&#39;&lt;h1 style=&quot;text-align: center;&quot;&gt;Welcome to the Todo List API!&lt;/h1&gt;&#39;);<br>});<br>// Start server<br>const port = 5000;<br>// Listen on port<br>app.listen(port, () =&gt; {<br>    console.log(`Running at - http://localhost:${port}`);<br>});</pre><ul><li>Now run npm start and test the application if the app is running or not.</li><li>Now redirect to — <a href="http://localhost:5000/">http://localhost:5000</a> and check into the browser. And you can show like below screenshot.</li></ul><figure><img alt="todo list with mysql, redis" src="https://cdn-images-1.medium.com/max/624/1*CXm1pO642FW2rLnAKloTEA.png" /></figure><h4>Create a Read/List route</h4><ul><li>Create a route in index.js like this.</li></ul><pre>// Fetching data from Database or Redis<br>app.get(&#39;/todos&#39;, async (req, res) =&gt; {<br>    try {<br>        // Check if cached data exists in Redis or not. If yes, return cached data<br>        const cachedData = await redisClient.get(&#39;todos&#39;);<br>        if (cachedData) {<br>            return res.send({<br>                success: true,<br>                message: &#39;Todos retrieved from cache successfully!&#39;,<br>                data   : JSON.parse(cachedData)<br>            });<br>        }<br><br>        // If cached data doesn&#39;t exist, fetch data from database and cache it<br>        const results = await new Promise((resolve, reject) =&gt; {<br>            DB.query(&#39;SELECT * FROM todos&#39;, (err, results) =&gt; {<br>                if (err) reject(err);<br>                resolve(results);<br>            });<br>        });<br><br>        // If no data found in database, return error message<br>        if (!results.length) {<br>            return res.send({<br>                success: false,<br>                message: &#39;No todos found!&#39;,<br>                data   : results<br>            });<br>        }<br><br>        // Cache data in Redis for 1 hour (3600 seconds)<br>        redisClient.setEx(&#39;todos&#39;, 3600, JSON.stringify(results));<br><br>        // Return response<br>        return res.send({<br>            success: true,<br>            message: &#39;Todos retrieved from database successfully!&#39;,<br>            data   : results<br>        });<br>    } catch (error) { // Catch any error<br>        throw error;<br>    }<br>});</pre><ul><li>Now open Postman and hit the URL in Postman and check response comes successfully.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mcCoohEj6lNRCKOdI8DdQ.png" /><figcaption>Fetch response</figcaption></figure><h4>Create ADD route</h4><ul><li>Create a route in index.js like this.</li></ul><pre>// Create new todo/ Add todo<br>app.post(&#39;/todos&#39;, (req, res) =&gt; {<br>    // Get data from request body<br>    const {title, description} = req.body;<br><br>    // Insert todo into database<br>    DB.query(&#39;INSERT INTO todos (title, description) VALUES (?, ?)&#39;, [title, description], (err, results) =&gt; {<br>        if (err) throw err; // Throw error if any<br><br>        // If no rows affected, then todo not inserted<br>        if (!results.affectedRows) {<br>            return res.send({<br>                success: false,<br>                message: &#39;Todo not added!&#39;,<br>                data   : results<br>            });<br>        }<br><br>        // Delete cached data from Redis<br>        redisClient.del(&#39;todos&#39;);<br><br>        // Return response<br>        return res.send({<br>            success: true,<br>            message: &#39;Todo added successfully!&#39;,<br>            data   : {<br>                id: results.insertId,<br>                title,<br>                description<br>            }<br>        });<br>    });<br>});</pre><ul><li>Now test into Postman by showing screenshots.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGgFjlTlVTiU2B9FMIW6rQ.png" /><figcaption>Create/Add Todo Like this</figcaption></figure><h4>Create UPDATE route</h4><ul><li>Create a route in index.js like this.</li></ul><pre>// Update todo<br>app.put(&#39;/todos/:id&#39;, (req, res) =&gt; {<br>    // Get data from request body<br>    const {title, description} = req.body;<br><br>    // Update todo in database<br>    DB.query(&#39;UPDATE todos SET title = ?, description = ? WHERE id = ?&#39;, [title, description, req.params.id], (err, results) =&gt; {<br>        if (err) throw err; // Throw error if any<br><br>        // If no rows affected, then todo not updated<br>        if (!results.affectedRows) {<br>            return res.send({<br>                success: false,<br>                message: &#39;Todo not updated!&#39;,<br>                data   : results<br>            });<br>        }<br><br>        // Delete cached data from Redis<br>        redisClient.del(&#39;todos&#39;);<br><br>        // Return response<br>        return res.send({<br>            success: true,<br>            message: &#39;Todo updated successfully!&#39;,<br>            data   : {<br>                id: req.params.id,<br>                title,<br>                description<br>            }<br>        });<br>    });<br>});</pre><ul><li>Now test into Postman by showing screenshots.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMiCWxVuLZJ34qySjkW3ug.png" /><figcaption>Update Todo like this</figcaption></figure><h4>Create DELETE route</h4><ul><li>Create a route in index.js like this.</li></ul><pre>// Delete todo<br>app.delete(&#39;/todos/:id&#39;, (req, res) =&gt; {<br>    DB.query(&#39;DELETE FROM todos WHERE id = ?&#39;, [req.params.id], (err, results) =&gt; {<br>        if (err) throw err; // Throw error if any<br><br>        // If no rows affected, then todo not deleted<br>        if (!results.affectedRows) {<br>            return res.send({<br>                success: false,<br>                message: &#39;Todo not deleted!&#39;,<br>                data   : results<br>            });<br>        }<br><br>        // Delete cached data from Redis<br>        redisClient.del(&#39;todos&#39;);<br><br>        // Return response<br>        return res.send({<br>            success: true,<br>            message: &#39;Todo deleted successfully!&#39;<br>        });<br>    });<br>});</pre><ul><li>Now test into Postman by showing screenshots.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jRyOnQWPQ5w0ZsX_IM5jQ.png" /><figcaption>Delete Todo Like this</figcaption></figure><h4>Now merge all code and show like this:</h4><pre>const cors    = require(&quot;cors&quot;);<br>const express = require(&quot;express&quot;);<br>const app     = express();<br>const mysql   = require(&#39;mysql&#39;);<br>const redis   = require(&#39;redis&#39;);<br><br>// Set up CORS<br>const corsOptions = {<br>    origin: &quot;http://localhost:3000&quot;<br>};<br>app.use(cors(corsOptions));<br><br>// Set json for getting data from request body<br>app.use(express.json());<br><br>// Redis setup<br>let redisClient;<br>(async () =&gt; {<br>    redisClient = redis.createClient();<br><br>    redisClient.on(&quot;error&quot;, (error) =&gt; console.error(`Error : ${error}`));<br><br>    redisClient.on(&quot;connect&quot;, () =&gt; console.log(&quot;Redis connected&quot;));<br><br>    await redisClient.connect();<br>})();<br><br>// MySQL setup<br>const DB = mysql.createConnection({<br>    host    : &#39;localhost&#39;,<br>    user    : &#39;root&#39;,<br>    password: &#39;toor&#39;,<br>    database: &#39;todo_list&#39;,<br>});<br><br>// Connect to MySQL<br>DB.connect((err) =&gt; {<br>    if (err) throw err;<br>    console.log(&#39;MySQL connected&#39;);<br>});<br><br>// Routes<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    res.send(&#39;&lt;h1 style=&quot;text-align: center;&quot;&gt;Welcome to the Todo List API!&lt;/h1&gt;&#39;);<br>});<br><br>// Fetching data from Database or Redis<br>app.get(&#39;/todos&#39;, async (req, res) =&gt; {<br>    try {<br>        // Check if cached data exists in Redis or not. If yes, return cached data<br>        const cachedData = await redisClient.get(&#39;todos&#39;);<br>        if (cachedData) {<br>            return res.send({<br>                success: true,<br>                message: &#39;Todos retrieved from cache successfully!&#39;,<br>                data   : JSON.parse(cachedData)<br>            });<br>        }<br><br>        // If cached data doesn&#39;t exist, fetch data from database and cache it<br>        const results = await new Promise((resolve, reject) =&gt; {<br>            DB.query(&#39;SELECT * FROM todos&#39;, (err, results) =&gt; {<br>                if (err) reject(err);<br>                resolve(results);<br>            });<br>        });<br><br>        // If no data found in database, return error message<br>        if (!results.length) {<br>            return res.send({<br>                success: false,<br>                message: &#39;No todos found!&#39;,<br>                data   : results<br>            });<br>        }<br><br>        // Cache data in Redis for 1 hour (3600 seconds)<br>        redisClient.setEx(&#39;todos&#39;, 3600, JSON.stringify(results));<br><br>        // Return response<br>        return res.send({<br>            success: true,<br>            message: &#39;Todos retrieved from database successfully!&#39;,<br>            data   : results<br>        });<br>    } catch (error) { // Catch any error<br>        throw error;<br>    }<br>});<br><br><br>// Create new todo/ Add todo<br>app.post(&#39;/todos&#39;, (req, res) =&gt; {<br>    // Get data from request body<br>    const {title, description} = req.body;<br><br>    // Insert todo into database<br>    DB.query(&#39;INSERT INTO todos (title, description) VALUES (?, ?)&#39;, [title, description], (err, results) =&gt; {<br>        if (err) throw err; // Throw error if any<br><br>        // If no rows affected, then todo not inserted<br>        if (!results.affectedRows) {<br>            return res.send({<br>                success: false,<br>                message: &#39;Todo not added!&#39;,<br>                data   : results<br>            });<br>        }<br><br>        // Delete cached data from Redis<br>        redisClient.del(&#39;todos&#39;);<br><br>        // Return response<br>        return res.send({<br>            success: true,<br>            message: &#39;Todo added successfully!&#39;,<br>            data   : {<br>                id: results.insertId,<br>                title,<br>                description<br>            }<br>        });<br>    });<br>});<br><br>// Update todo<br>app.put(&#39;/todos/:id&#39;, (req, res) =&gt; {<br>    // Get data from request body<br>    const {title, description} = req.body;<br><br>    // Update todo in database<br>    DB.query(&#39;UPDATE todos SET title = ?, description = ? WHERE id = ?&#39;, [title, description, req.params.id], (err, results) =&gt; {<br>        if (err) throw err; // Throw error if any<br><br>        // If no rows affected, then todo not updated<br>        if (!results.affectedRows) {<br>            return res.send({<br>                success: false,<br>                message: &#39;Todo not updated!&#39;,<br>                data   : results<br>            });<br>        }<br><br>        // Delete cached data from Redis<br>        redisClient.del(&#39;todos&#39;);<br><br>        // Return response<br>        return res.send({<br>            success: true,<br>            message: &#39;Todo updated successfully!&#39;,<br>            data   : {<br>                id: req.params.id,<br>                title,<br>                description<br>            }<br>        });<br>    });<br>});<br><br>// Delete todo<br>app.delete(&#39;/todos/:id&#39;, (req, res) =&gt; {<br>    DB.query(&#39;DELETE FROM todos WHERE id = ?&#39;, [req.params.id], (err, results) =&gt; {<br>        if (err) throw err; // Throw error if any<br><br>        // If no rows affected, then todo not deleted<br>        if (!results.affectedRows) {<br>            return res.send({<br>                success: false,<br>                message: &#39;Todo not deleted!&#39;,<br>                data   : results<br>            });<br>        }<br><br>        // Delete cached data from Redis<br>        redisClient.del(&#39;todos&#39;);<br><br>        // Return response<br>        return res.send({<br>            success: true,<br>            message: &#39;Todo deleted successfully!&#39;<br>        });<br>    });<br>});<br><br>// Start server<br>const port = 5000;<br><br>// Listen on port<br>app.listen(port, () =&gt; {<br>    console.log(`Running at - http://localhost:${port}`);<br>});</pre><p>Run this project by running this command npm start and test all endpoints.</p><h3>The CRUD with React.js</h3><h4>Configure App.js file for CRUD</h4><ul><li>Do like this in App.js</li></ul><pre>import &#39;bootstrap/dist/css/bootstrap.css&#39;;<br>import axios from &quot;axios&quot;;<br>import {useState} from &quot;react&quot;;<br><br>const App = () =&gt; {<br>    // Backend API URL<br>    const baseUrl = &#39;http://localhost:5000/todos&#39;;<br>    const [todos, setTodos]             = useState([]);<br>    const [title, setTitle]             = useState(&#39;&#39;);<br>    const [description, setDescription] = useState(&#39;&#39;);<br>    const [todoId, setTodoId]           = useState(null);<br>    const [isEdit, setIsEdit]           = useState(false);<br>    const [successMsg, setSuccessMsg]   = useState(null);<br>    const [errorMsg, setErrorMsg]       = useState(null);<br>    // Cancel/Reset todo form<br>    const cancelTodoHandler = () =&gt; {<br>        setTitle(&#39;&#39;);<br>        setDescription(&#39;&#39;);<br>        setIsEdit(false);<br>    };<br>    // Hide success/error message after 5 seconds<br>    const hideMsg = () =&gt; {<br>        setTimeout(() =&gt; {<br>            setSuccessMsg(null);<br>            setErrorMsg(null);<br>        }, 5000);<br>    };<br>    return (<br>        &lt;div className=&quot;container&quot;&gt;<br>            &lt;h1 className=&quot;h1 text-center&quot;&gt;Todo APP&lt;/h1&gt;<br>            &lt;div className=&quot;row justify-content-center&quot;&gt;<br>                &lt;div className=&quot;col-md-8&quot;&gt;<br>                    &lt;div className=&quot;card mb-4&quot;&gt;<br>                        &lt;div className=&quot;card-header&quot;&gt;<br>                            &lt;h4 className=&quot;card-title&quot;&gt;<br>                                Add Todo<br>                            &lt;/h4&gt;<br>                        &lt;/div&gt;<br>                        &lt;form &gt;<br>                            &lt;div className=&quot;card-body&quot;&gt;<br>                                &lt;div className=&quot;form-group mb-3&quot;&gt;<br>                                    &lt;label htmlFor=&quot;title&quot; className=&quot;form-label&quot;&gt;Title&lt;/label&gt;<br>                                    &lt;input type=&quot;text&quot; id=&quot;title&quot; name=&quot;title&quot; className=&quot;form-control&quot;<br>                                           placeholder=&quot;Enter title&quot; required autoFocus value={title}<br>                                           onChange={e =&gt; setTitle(e.target.value)}/&gt;<br>                                &lt;/div&gt;<br>                                &lt;div className=&quot;form-group&quot;&gt;<br>                                    &lt;label htmlFor=&quot;description&quot; className=&quot;form-label&quot;&gt;Description&lt;/label&gt;<br>                                    &lt;textarea className=&quot;form-control&quot; name=&quot;description&quot;<br>                                              id=&quot;description&quot; cols=&quot;30&quot; rows=&quot;10&quot;<br>                                              placeholder=&quot;Enter description&quot; required value={description}<br>                                              onChange={e =&gt; setDescription(e.target.value)}&gt;&lt;/textarea&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div className=&quot;card-footer&quot;&gt;<br>                                &lt;p className=&quot;text-end&quot;&gt;<br>                                    &lt;button type=&quot;button&quot; className=&quot;btn btn-danger btn-lg&quot; onClick={cancelTodoHandler}&gt;<br>                                        Cancel<br>                                    &lt;/button&gt;<br>                                    {isEdit ?<br>                                        &lt;button type=&quot;submit&quot; className=&quot;btn btn-primary btn-lg ms-2&quot;&gt;<br>                                            Update<br>                                        &lt;/button&gt; :<br>                                        &lt;button type=&quot;submit&quot; className=&quot;btn btn-primary btn-lg ms-2&quot;&gt;<br>                                            Save<br>                                        &lt;/button&gt;}<br>                                &lt;/p&gt;<br>                            &lt;/div&gt;<br>                        &lt;/form&gt;<br>                    &lt;/div&gt;<br>                    {successMsg &amp;&amp;<br>                        &lt;div className=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;<br>                            {successMsg}<br>                        &lt;/div&gt;<br>                    }<br>                    {errorMsg &amp;&amp;<br>                        &lt;div className=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;<br>                            {errorMsg}<br>                        &lt;/div&gt;<br>                    }<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;row mt-5 mb-5&quot;&gt;<br>                &lt;div className=&quot;col-md-12&quot;&gt;<br>                    &lt;div className=&quot;card&quot;&gt;<br>                        &lt;div className=&quot;card-header&quot;&gt;<br>                            &lt;h4 className=&quot;card-title&quot;&gt;<br>                                Todo List<br>                            &lt;/h4&gt;<br>                        &lt;/div&gt;<br>                        &lt;div className=&quot;card-body&quot;&gt;<br>                            &lt;div className=&quot;table-responsive&quot;&gt;<br>                                &lt;table className=&quot;table table-bordered table-hover table-striped&quot;&gt;<br>                                    &lt;thead&gt;<br>                                    &lt;tr&gt;<br>                                        &lt;th className=&quot;text-center&quot;&gt;SL#&lt;/th&gt;<br>                                        &lt;th&gt;Title&lt;/th&gt;<br>                                        &lt;th&gt;Description&lt;/th&gt;<br>                                        &lt;th className=&quot;text-center&quot;&gt;Action&lt;/th&gt;<br>                                    &lt;/tr&gt;<br>                                    &lt;/thead&gt;<br>                                    &lt;tbody&gt;<br>                                    {todos.map((todo, index) =&gt; (<br>                                        &lt;tr key={index}&gt;<br>                                            &lt;td className=&quot;text-center&quot;&gt;{index + 1}&lt;/td&gt;<br>                                            &lt;td&gt;{todo.title}&lt;/td&gt;<br>                                            &lt;td&gt;<br>                                                {todo.description.length &gt; 50 ? todo.description.substring(0, 50) + &#39;...&#39; : todo.description}<br>                                            &lt;/td&gt;<br>                                            &lt;td className=&quot;text-center&quot;&gt;<br>                                                &lt;button type=&quot;button&quot; className=&quot;btn btn-sm btn-primary btn-sm&quot;&gt;<br>                                                    Edit<br>                                                &lt;/button&gt;<br>                                                &lt;button type=&quot;button&quot; className=&quot;btn btn-sm btn-danger btn-sm ms-2&quot;&gt;<br>                                                    Delete<br>                                                &lt;/button&gt;<br>                                            &lt;/td&gt;<br>                                        &lt;/tr&gt;<br>                                    ))}<br>                                    &lt;/tbody&gt;<br>                                &lt;/table&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>}<br><br>export default App;</pre><h4>Create a Read request</h4><ul><li>Create Axios <strong>GET</strong> request in App.js for fetching to-do list.</li></ul><pre>// Fetch all todos<br>const getTodos = async () =&gt; {<br>    try {<br>        // Fetch data from backend<br>        const response = await axios.get(`${baseUrl}`);<br><br>        // Set todos data to todos state<br>        setTodos(response.data.data);<br><br>        // Show success message<br>        setSuccessMsg(response.data.message);<br>    } catch (error) {<br>        console.log(error.response);<br><br>        // Show error message<br>        setErrorMsg(error.response.data.message);<br>    } finally {<br>        // Hide success/error message after 5 seconds<br>        hideMsg();<br>    }<br>};</pre><h4>Create POST request for create/add todo</h4><ul><li>Create Axios <strong>POST</strong> request in App.js for <strong>create/add</strong> todo.</li></ul><pre>// Add new todo<br>const addTodoHandler = async (e) =&gt; {<br>    // Prevent default form submission<br>    e.preventDefault();<br>    try {<br>        // Send post request to backend by sending title and description<br>        const response = await axios.post(`${baseUrl}`, {title, description});<br><br>        // Add new todo and update todos state<br>        setTodos([...todos, response.data.data]);<br><br>        // Reset todo form<br>        setTitle(&#39;&#39;);<br>        setDescription(&#39;&#39;);<br><br>        // Show success message<br>        setSuccessMsg(response.data.message);<br>    } catch (error) {<br>        console.log(error.response);<br>        // Show error message<br>        setErrorMsg(error.response.data.message);<br>    } finally {<br>        // Hide success/error message after 5 seconds<br>        hideMsg();<br>    }<br>};</pre><h4>Create PUT request for update todo</h4><ul><li>Create Axios <strong>PUT</strong> request in App.js for <strong>update</strong> todo.</li></ul><pre>// Edit todo<br>const editTodoHandler = async (todo) =&gt; {<br>    // Set todo data to todo form<br>    setTitle(todo.title);<br>    setDescription(todo.description);<br>    setTodoId(todo.id);<br>    setIsEdit(true);<br>};<br><br>// Update todo<br>const updateTodoHandler = async (e) =&gt; {<br>// Prevent default form submission<br>e.preventDefault();<br>try {<br>    // Send put request to backend by sending title and description<br>    const response     = await axios.put(`${baseUrl}/${todoId}`, {title, description});<br><br>    // Update todo in todos state<br>    const updatedTodos = todos.map(todo =&gt; {<br>        if (todo.id === todoId) {<br>            todo.title       = title;<br>            todo.description = description;<br>        }<br>        return todo;<br>    });<br><br>    // Update todos state<br>    setTodos(updatedTodos);<br><br>    // Reset todo form<br>    setTitle(&#39;&#39;);<br>    setDescription(&#39;&#39;);<br>    setTodoId(null);<br>    setIsEdit(false);<br><br>    // Show success message<br>    setSuccessMsg(response.data.message);<br>} catch (error) {<br>    console.log(error.response);<br>    // Show error message<br>    setErrorMsg(error.response.data.message);<br>} finally {<br>    // Hide success/error message after 5 seconds<br>    hideMsg();<br>}<br>};</pre><h4>Create DELETE request for delete todo</h4><ul><li>Create Axios <strong>DELETE</strong> request in App.js for <strong>delete</strong> todo.</li></ul><pre>// Delete todo<br>const deleteTodoHandler = async (id) =&gt; {<br>try {<br>    // Send delete request to backend<br>    const response      = await axios.delete(`${baseUrl}/${id}`);<br><br>    // Remove todo from todos state<br>    const filteredTodos = todos.filter(todo =&gt; todo.id !== id);<br><br>    // Update todos state<br>    setTodos(filteredTodos);<br><br>    // Show success message<br>    setSuccessMsg(response.data.message);<br>} catch (error) {<br>    console.log(error.response);<br>    // Show error message<br>    setErrorMsg(error.response.data.message);<br>} finally {<br>    // Hide success/error message after 5 seconds<br>    hideMsg();<br>}<br>};</pre><h4>Now merge all code and show like this:</h4><pre>import &#39;bootstrap/dist/css/bootstrap.css&#39;;<br>import axios from &quot;axios&quot;;<br>import {useEffect, useState} from &quot;react&quot;;<br><br>const App = () =&gt; {<br>    // Backend API URL<br>    const baseUrl = &#39;http://localhost:5000/todos&#39;;<br><br>    const [todos, setTodos]             = useState([]);<br>    const [title, setTitle]             = useState(&#39;&#39;);<br>    const [description, setDescription] = useState(&#39;&#39;);<br>    const [todoId, setTodoId]           = useState(null);<br>    const [isEdit, setIsEdit]           = useState(false);<br>    const [successMsg, setSuccessMsg]   = useState(null);<br>    const [errorMsg, setErrorMsg]       = useState(null);<br><br>    // Fetch all todos<br>    const getTodos = async () =&gt; {<br>        try {<br>            // Fetch data from backend<br>            const response = await axios.get(`${baseUrl}`);<br><br>            // Set todos data to todos state<br>            setTodos(response.data.data);<br><br>            // Show success message<br>            setSuccessMsg(response.data.message);<br>        } catch (error) {<br>            console.log(error.response);<br><br>            // Show error message<br>            setErrorMsg(error.response.data.message);<br>        } finally {<br>            // Hide success/error message after 5 seconds<br>            hideMsg();<br>        }<br>    };<br><br>    // Add new todo<br>    const addTodoHandler = async (e) =&gt; {<br>        // Prevent default form submission<br>        e.preventDefault();<br>        try {<br>            // Send post request to backend by sending title and description<br>            const response = await axios.post(`${baseUrl}`, {title, description});<br><br>            // Add new todo and update todos state<br>            setTodos([...todos, response.data.data]);<br><br>            // Reset todo form<br>            setTitle(&#39;&#39;);<br>            setDescription(&#39;&#39;);<br><br>            // Show success message<br>            setSuccessMsg(response.data.message);<br>        } catch (error) {<br>            console.log(error.response);<br>            // Show error message<br>            setErrorMsg(error.response.data.message);<br>        } finally {<br>            // Hide success/error message after 5 seconds<br>            hideMsg();<br>        }<br>    };<br><br>    // Cancel/Reset todo form<br>    const cancelTodoHandler = () =&gt; {<br>        setTitle(&#39;&#39;);<br>        setDescription(&#39;&#39;);<br>        setIsEdit(false);<br>    };<br><br>    // Edit todo<br>    const editTodoHandler = async (todo) =&gt; {<br>        // Set todo data to todo form<br>        setTitle(todo.title);<br>        setDescription(todo.description);<br>        setTodoId(todo.id);<br>        setIsEdit(true);<br>    };<br><br>    // Update todo<br>    const updateTodoHandler = async (e) =&gt; {<br>        // Prevent default form submission<br>        e.preventDefault();<br>        try {<br>            // Send put request to backend by sending title and description<br>            const response     = await axios.put(`${baseUrl}/${todoId}`, {title, description});<br><br>            // Update todo in todos state<br>            const updatedTodos = todos.map(todo =&gt; {<br>                if (todo.id === todoId) {<br>                    todo.title       = title;<br>                    todo.description = description;<br>                }<br>                return todo;<br>            });<br><br>            // Update todos state<br>            setTodos(updatedTodos);<br><br>            // Reset todo form<br>            setTitle(&#39;&#39;);<br>            setDescription(&#39;&#39;);<br>            setTodoId(null);<br>            setIsEdit(false);<br><br>            // Show success message<br>            setSuccessMsg(response.data.message);<br>        } catch (error) {<br>            console.log(error.response);<br>            // Show error message<br>            setErrorMsg(error.response.data.message);<br>        } finally {<br>            // Hide success/error message after 5 seconds<br>            hideMsg();<br>        }<br>    };<br><br>    // Delete todo<br>    const deleteTodoHandler = async (id) =&gt; {<br>        try {<br>            // Send delete request to backend<br>            const response      = await axios.delete(`${baseUrl}/${id}`);<br><br>            // Remove todo from todos state<br>            const filteredTodos = todos.filter(todo =&gt; todo.id !== id);<br><br>            // Update todos state<br>            setTodos(filteredTodos);<br><br>            // Show success message<br>            setSuccessMsg(response.data.message);<br>        } catch (error) {<br>            console.log(error.response);<br>            // Show error message<br>            setErrorMsg(error.response.data.message);<br>        } finally {<br>            // Hide success/error message after 5 seconds<br>            hideMsg();<br>        }<br>    };<br><br>    // Submit handler<br>    const submitHandler = async (e) =&gt; {<br>        // Conditionally call addTodoHandler or updateTodoHandler<br>        if (isEdit) {<br>            await updateTodoHandler(e);<br>        } else {<br>            await addTodoHandler(e);<br>        }<br>    };<br><br>    // Hide success/error message after 5 seconds<br>    const hideMsg = () =&gt; {<br>        setTimeout(() =&gt; {<br>            setSuccessMsg(null);<br>            setErrorMsg(null);<br>        }, 5000);<br>    };<br><br><br>    // Fetch all todos on page load or component mounted<br>    useEffect(() =&gt; {<br>        getTodos();<br>    }, []);<br><br>    return (<br>        &lt;div className=&quot;container&quot;&gt;<br>            &lt;h1 className=&quot;h1 text-center&quot;&gt;Todo APP&lt;/h1&gt;<br>            &lt;div className=&quot;row justify-content-center&quot;&gt;<br>                &lt;div className=&quot;col-md-8&quot;&gt;<br>                    &lt;div className=&quot;card mb-4&quot;&gt;<br>                        &lt;div className=&quot;card-header&quot;&gt;<br>                            &lt;h4 className=&quot;card-title&quot;&gt;<br>                                Add Todo<br>                            &lt;/h4&gt;<br>                        &lt;/div&gt;<br>                        &lt;form onSubmit={submitHandler}&gt;<br>                            &lt;div className=&quot;card-body&quot;&gt;<br>                                &lt;div className=&quot;form-group mb-3&quot;&gt;<br>                                    &lt;label htmlFor=&quot;title&quot; className=&quot;form-label&quot;&gt;Title&lt;/label&gt;<br>                                    &lt;input type=&quot;text&quot; id=&quot;title&quot; name=&quot;title&quot; className=&quot;form-control&quot;<br>                                           placeholder=&quot;Enter title&quot; required autoFocus value={title}<br>                                           onChange={e =&gt; setTitle(e.target.value)}/&gt;<br>                                &lt;/div&gt;<br>                                &lt;div className=&quot;form-group&quot;&gt;<br>                                    &lt;label htmlFor=&quot;description&quot; className=&quot;form-label&quot;&gt;Description&lt;/label&gt;<br>                                    &lt;textarea className=&quot;form-control&quot; name=&quot;description&quot;<br>                                              id=&quot;description&quot; cols=&quot;30&quot; rows=&quot;10&quot;<br>                                              placeholder=&quot;Enter description&quot; required value={description}<br>                                              onChange={e =&gt; setDescription(e.target.value)}&gt;&lt;/textarea&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            &lt;div className=&quot;card-footer&quot;&gt;<br>                                &lt;p className=&quot;text-end&quot;&gt;<br>                                    &lt;button type=&quot;button&quot; className=&quot;btn btn-danger btn-lg&quot; onClick={cancelTodoHandler}&gt;<br>                                        Cancel<br>                                    &lt;/button&gt;<br>                                    {isEdit ?<br>                                        &lt;button type=&quot;submit&quot; className=&quot;btn btn-primary btn-lg ms-2&quot;&gt;<br>                                            Update<br>                                        &lt;/button&gt; :<br>                                        &lt;button type=&quot;submit&quot; className=&quot;btn btn-primary btn-lg ms-2&quot;&gt;<br>                                            Save<br>                                        &lt;/button&gt;}<br>                                &lt;/p&gt;<br>                            &lt;/div&gt;<br>                        &lt;/form&gt;<br>                    &lt;/div&gt;<br><br>                    {successMsg &amp;&amp;<br>                        &lt;div className=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;<br>                            {successMsg}<br>                        &lt;/div&gt;<br>                    }<br><br>                    {errorMsg &amp;&amp;<br>                        &lt;div className=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;<br>                            {errorMsg}<br>                        &lt;/div&gt;<br>                    }<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;div className=&quot;row mt-5 mb-5&quot;&gt;<br>                &lt;div className=&quot;col-md-12&quot;&gt;<br>                    &lt;div className=&quot;card&quot;&gt;<br>                        &lt;div className=&quot;card-header&quot;&gt;<br>                            &lt;h4 className=&quot;card-title&quot;&gt;<br>                                Todo List<br>                            &lt;/h4&gt;<br>                        &lt;/div&gt;<br>                        &lt;div className=&quot;card-body&quot;&gt;<br>                            &lt;div className=&quot;table-responsive&quot;&gt;<br>                                &lt;table className=&quot;table table-bordered table-hover table-striped&quot;&gt;<br>                                    &lt;thead&gt;<br>                                    &lt;tr&gt;<br>                                        &lt;th className=&quot;text-center&quot;&gt;SL#&lt;/th&gt;<br>                                        &lt;th&gt;Title&lt;/th&gt;<br>                                        &lt;th&gt;Description&lt;/th&gt;<br>                                        &lt;th className=&quot;text-center&quot;&gt;Action&lt;/th&gt;<br>                                    &lt;/tr&gt;<br>                                    &lt;/thead&gt;<br>                                    &lt;tbody&gt;<br>                                    {todos.map((todo, index) =&gt; (<br>                                        &lt;tr key={index}&gt;<br>                                            &lt;td className=&quot;text-center&quot;&gt;{index + 1}&lt;/td&gt;<br>                                            &lt;td&gt;{todo.title}&lt;/td&gt;<br>                                            &lt;td&gt;<br>                                                {todo.description.length &gt; 50 ? todo.description.substring(0, 50) + &#39;...&#39; : todo.description}<br>                                            &lt;/td&gt;<br>                                            &lt;td className=&quot;text-center&quot;&gt;<br>                                                &lt;button type=&quot;button&quot; className=&quot;btn btn-sm btn-primary btn-sm&quot;<br>                                                        onClick={editTodoHandler.bind(this, todo)}&gt;<br>                                                    Edit<br>                                                &lt;/button&gt;<br>                                                &lt;button type=&quot;button&quot; className=&quot;btn btn-sm btn-danger btn-sm ms-2&quot;<br>                                                        onClick={deleteTodoHandler.bind(this, todo.id)}&gt;<br>                                                    Delete<br>                                                &lt;/button&gt;<br>                                            &lt;/td&gt;<br>                                        &lt;/tr&gt;<br>                                    ))}<br>                                    &lt;/tbody&gt;<br>                                &lt;/table&gt;<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>}<br><br>export default App;</pre><ul><li>Run this project by running this command npm start and test all endpoints.</li><li>Open the project in the browser and test the project.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*run2VFouECuDbdy5cmETVw.png" /><figcaption>Web View</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCwI3Ke-6Oazy1MtvGr-9Q.png" /></figure><ul><li>So, in this article, we learned about four basic CRUD operations using Node.js(EXPRESS) and React.js. Also learned about MySQL and Redis tools.</li><li>I hope you find this article interesting and learned something useful.</li><li>Thanks for reading this article.</li></ul><h3>— — — — — — — — Happy Coding — — — — — — — — —</h3><ul><li>You can connect with me on <a href="https://github.com/mishajib/">Github</a> and <a href="https://www.linkedin.com/in/mishajib/">Linkedin</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c21275a8211d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>