<?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 Rajat Dhoot on Medium]]></title>
        <description><![CDATA[Stories by Rajat Dhoot on Medium]]></description>
        <link>https://medium.com/@rajatdhoot?source=rss-54d252ec8593------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZyOxVT3cyAbIQvgq.jpg</url>
            <title>Stories by Rajat Dhoot on Medium</title>
            <link>https://medium.com/@rajatdhoot?source=rss-54d252ec8593------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:00:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajatdhoot/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[Creating Backend — MERN Blog Application — Part 2]]></title>
            <link>https://medium.com/@rajatdhoot/creating-backend-mern-blog-application-part-2-e6b807666b8?source=rss-54d252ec8593------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6b807666b8</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[mern]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[blog]]></category>
            <dc:creator><![CDATA[Rajat Dhoot]]></dc:creator>
            <pubDate>Thu, 29 Aug 2019 18:31:01 GMT</pubDate>
            <atom:updated>2019-08-29T18:31:01.680Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating Backend — MERN Blog Application — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JsClH04ugmN_ZdDNZs1Rkw.gif" /><figcaption>Bloggy — MERN Blog Application</figcaption></figure><p>Before continuing further, make sure you know the basics well. However, if you don’t, you can follow the Part-1 of this article series.</p><p><a href="https://medium.com/@rajatdhoot/learn-build-a-mern-stack-application-in-100-hours-part-1-ee56e3f61979">Learn &amp; Build a MERN Stack Application in 100 hours — Part 1</a></p><ol><li><strong>Configuration</strong></li></ol><ul><li><em>Code Editor — </em>You can download and configure any code editor of your choice (Atom, Sublime). I prefer using <a href="https://code.visualstudio.com/">VSCode</a>. After downloading, install these extensions for smoother development: Prettier (Enable Format on Save from Settings), Simple React Snippets, Path Intellisense, Bracket Pair Colorizer</li><li>Install <a href="https://nodejs.org/en/download/">Node.js</a>. <em>npm</em> is the default package manager for Node.js. Before proceeding ahead learn more about <a href="https://nodesource.com/blog/an-absolute-beginners-guide-to-using-npm/">npm</a>.</li><li>Let’s create a root folder and initialize npm.</li></ul><pre>mkdir blogApplication<br>cd blogApplication<br>npm init (Press Enter to continue ahead)</pre><ul><li>Now, let’s install the dependencies required for this project. We will learn more about these packages when we will use them.</li></ul><pre>npm i express mongoose dotenv passport passport-jwt validator is-empty jsonwebtoken bcryptjs body-parser concurrently</pre><ul><li><em>Nodemon — A u</em>tility that monitors changes done to your code and restarts your server whenever you save those changes. Since we don’t need this package in the production environment, so we will include it as a dev-dependency by specifying the flag -D.</li></ul><pre>npm i nodemon -D</pre><p>Set the ‘<em>main</em>’ entry point to ‘<em>server.js’</em> instead of ‘<em>index.js’</em>. Add the highlighted scripts mentioned below. Your package.json file should resemble this</p><pre>{<br> &quot;name:&quot;blog&quot;,<br> &quot;version&quot;: &quot;1.0.0&quot;,<br> &quot;description&quot;:&quot;Mern Blog Application&quot;,<br> &quot;<strong>main</strong>&quot;: &quot;<strong>server.js</strong>&quot;,<br> &quot;<strong>scripts</strong>&quot;: {<br>   &quot;<strong>start</strong>&quot;: &quot;<strong>node server.js</strong>&quot;,<br>   &quot;<strong>server</strong>&quot;: &quot;<strong>nodemon server.js</strong>&quot;<br> },<br> &quot;author&quot;: &quot;&quot;,<br> &quot;license&quot;: &quot;ISC&quot;,<br>&quot;dependencies&quot;: {<br>  &quot;bcryptjs&quot;: &quot;^2.4.3&quot;,<br>  &quot;body-parser&quot;: &quot;^1.19.0&quot;,<br>  &quot;concurrently&quot;: &quot;^4.1.2&quot;,<br>  &quot;dotenv&quot;: &quot;^8.1.0&quot;,<br>  &quot;express&quot;: &quot;^4.17.1&quot;,<br>  &quot;is-empty&quot;: &quot;^1.2.0&quot;,<br>  &quot;jsonwebtoken&quot;: &quot;^8.5.1&quot;,<br>  &quot;mongoose&quot;: &quot;^5.6.11&quot;,<br>  &quot;passport&quot;: &quot;^0.4.0&quot;,<br>  &quot;passport-jwt&quot;: &quot;^4.0.0&quot;,<br>  &quot;validator&quot;: &quot;^11.1.0&quot;<br> }<br>}</pre><p>Later we will use <strong><em>nodemon run server</em> </strong>to initiate our server.</p><ul><li>Structure your folder directory similar to the one mentioned below.</li></ul><pre><strong>blogApplication</strong><br>    |<br>    | <strong>middleware </strong>(for jwt authentication)<strong><br>    </strong>      | passport.js<br>    | <strong>models </strong>(for MongoDB Model)<strong><br>          </strong>| Post.js<br>          | User.js<br>    | <strong>routes<br>          | api </strong>(for handling API routes)<strong><br>              </strong>| post.js<br>              | user.js<br>    | <strong>validation </strong>(for validating user input)<strong><br>    </strong>      | login.js<br>          | signup.js<br>          | post.js<br>    | .env<br>    | server.js<br>    | package.json</pre><ul><li><a href="https://docs.atlas.mongodb.com/getting-started/">Configure </a>your MongoDB Atlas account. You can whitelist all IPs by clicking ‘Allow Access from Anywhere’.</li><li>Download and install <a href="https://www.getpostman.com/products">POSTMAN</a>. We will use it for testing our APIs.</li></ul><p><strong>2. Setting Up Backend</strong></p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction"><strong>CREATING SERVER</strong></a><strong>:</strong> <br>Since we defined the entry point of our application to be <em>server.js, </em>open the file and add the following code<em>.</em></li></ul><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const PORT = process.env.PORT || 5000;</pre><pre>app.get(&quot;/&quot;, (req, res) =&gt; {<br>  res.send(&quot;hello&quot;);<br>});</pre><pre>app.listen(PORT, () =&gt; {<br>console.log(`Server up and running on port ${PORT}`);<br>});</pre><p>Here, we have imported express and initiated it. PORT contains the port number that your app should listen to. <em>process.env.PORT </em>is the way to access PORT number added in the environment variable (by hosting service providers). || 5000 is used for setting an alternate default value to PORT in case the former condition evaluates to undefined. Run ‘<strong><em>nodemon run server</em></strong><em>’ </em>from the root application directory. Visit <em>localhost:5000</em>, you should see a ‘hello’ response on the webpage.</p><p>We see a ‘<em>hello’</em> response since we have written an API which listens for request at ‘/’ and sends the response as ‘<em>hello</em>’. Let’s write another API that accepts user information and resends the same. Add the following lines to your code.</p><pre>app.post(&quot;/user&quot;, (req, res) =&gt; {<br>  console.log(req.body);<br>  res.send(req.body);<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*1VK_o2XQUUFRdsdjASGdzA.png" /><figcaption>POSTMAN — Making API post call to /user</figcaption></figure><p>So, we get undefined in the console and blank response on the POSTMAN. Why is that? Read this article on <a href="https://medium.com/@adamzerner/how-bodyparser-works-247897a93b90">bodyParser</a>() to understand why we need it.</p><ul><li>Let’s add body-parser in our code.</li></ul><pre>const express = require(&quot;express&quot;);<br><strong>const bodyParser = require(&quot;body-parser&quot;);<br></strong>const PORT = process.env.PORT || 5000;<br>const app = express();</pre><pre><strong>app.use(bodyParser.json());<br>app.use(bodyParser.urlencoded({ extended: false }));</strong></pre><pre>app.listen(PORT, () =&gt; {<br>  console.log(`Server up and running on port ${PORT}`);<br>});</pre><p>You can try out the APIs after adding body-parser, it should work. Remove these API handlers, we will add them later in this section.</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose"><strong>SETTING UP DATABASE</strong></a><strong>:<br></strong>We will use mongoose to connect to the database. Open your MongoAtlas account, open Cluster &gt; Connect &gt; Connect Your Application. Copy the connection string. Now, open the <strong><em>.env</em></strong> file and assign the connection string to MONGO_URI. Replace username and password with the one created during configuration. When entering your password, make sure that any special characters are URL encoded</li></ul><pre>MONGO_URI=&quot;mongodb://dbuser:dbpass@host:port/dbname&quot;</pre><p>In our server.js file, let us set up and connect our database.</p><pre>const express = require(&quot;express&quot;);<br><strong>require(&quot;dotenv&quot;).config();</strong> <em>// for loading environment variables<br></em>const bodyParser = require(&quot;body-parser&quot;);<br><strong>const mongoose = require(&quot;mongoose&quot;);</strong><br>const app = express();</pre><pre>app.use(bodyParser.json());<br>app.use(bodyParser.urlencoded({ extended: false }));</pre><pre><strong>const MONGO_URI = process.env.MONGO_URI;</strong></pre><pre><strong>mongoose<br>.connect(MONGO_URI, { useNewUrlParser: true })<br>.then(() =&gt; console.log(&quot;Mongo Connection successful&quot;))<br>.catch(err =&gt; console.log(&quot;err&quot;));</strong></pre><pre>const PORT = process.env.PORT || 5000;<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server up and running on port ${PORT}`);<br>});</pre><p>If you have done everything correctly, you should see ‘Mongo Connection Successful’ message in the console.</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose"><strong>CREATING SCHEMA</strong></a><strong> </strong>— <br>We will create two schemas, one containing User’s Information (user_name, email, password) and the other containing Post’s information (title, body, author, date). We will export the models created so that we can access it outside. Navigate to Models. Create two files User.js, Post.js</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61ee9728705b7dd97b79d66a30336c58/href">https://medium.com/media/61ee9728705b7dd97b79d66a30336c58/href</a></iframe><p>3. <strong>Creating Form Validations</strong></p><p>We are required to validate three input forms (Login, Signup, Post). We will create different files for each of them and export a function that accepts user data as input and returns an object with errors and isValid as properties. Since validators functions work only with strings we will convert all empty fields to empty string before validating them. Navigate to Validation. Create three files login.js, signup.js, post.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88aa8e0f83e0db52ec012e727591e568/href">https://medium.com/media/88aa8e0f83e0db52ec012e727591e568/href</a></iframe><p><strong>4.</strong> <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/routes"><strong>Setting Up Routes</strong></a><strong>, Creating APIs, Integrating </strong><a href="http://www.passportjs.org/packages/passport-jwt/"><strong>Passport </strong></a><strong>&amp; </strong><a href="https://medium.com/vandium-software/5-easy-steps-to-understanding-json-web-tokens-jwt-1164c0adfcec"><strong>JWT</strong></a></p><p>Initially, we created API routes using <em>app.get()/app.post() </em>method in server.js file. There is a better and modular approach to create routes using express.Router(). It allows you to group related routes together in one particular file, and separate those from un-related routes. So, instead of cluttering all of our routes in server.js we will use small modular files for defining them. We have two main areas of concern i.e. user (creation, authentication), and post (create, read, update and delete). So, we will create two different routes file — users.js, posts.js.</p><p><em>bcrypt </em>— it is used to hash the user’s password before storing it in a database.<br><a href="https://medium.com/vandium-software/5-easy-steps-to-understanding-json-web-tokens-jwt-1164c0adfcec"><em>jsonwebtoken </em></a>— used for authenticating the user</p><p>In the <strong><em>.env</em></strong><em> </em>file, create another variable <strong>SECRET </strong>and assign it any string of your choice. This secret would be used in signing the jwt token sent to the user on login.</p><ul><li>Let’s first handle user related routes (<strong>users.js</strong>). Importing the required dependencies.</li></ul><pre>const express = require(&quot;express&quot;);<br>const router = express.Router(); <br>const bcrypt = require(&quot;bcryptjs&quot;);<br>const jwt = require(&quot;jsonwebtoken&quot;);<br>const SECRET = process.env.SECRET; <br>const validateSignUpInput = require(&quot;../../validation/signup&quot;);<br>const validateLoginInput = require(&quot;../../validation/login&quot;);<br>const User = require(&quot;../../models/User&quot;);</pre><p><strong><em>Signup Route</em></strong><em> — </em>We start by validating user input. If it is invalid we return the appropriate error message to the user. Otherwise, we search our database for a user with the same username or email. If we find a user with the same email or username we return the corresponding error to the user, otherwise, we create a new user, hash the password and store the updated details in our database.</p><pre>router.post(&quot;/signup&quot;, (req, res) =&gt; {<br>   const {errors, isValid} = validateSignUpInput(req.body);<br>   const {user_name, email, password} = req.body;<br>   if (!isValid) {<br>      return res.status(400).json(errors);<br>   }<br>   User.findOne({$or:[{email},{user_name}]}).then(user =&gt; {<br>      if (user) {<br>         if (user.email === email)<br>            return res.status(400).json({ email: &quot;Email already exists&quot; });<br>         else<br>            return res<br>               .status(400)<br>               .json({ user_name: &quot;Username already exists&quot; });<br>      } else {<br>         const newUser = new User({ user_name, email, password });<br>         // hashing password before storing it in database<br>         bcrypt.genSalt(10, (err, salt) =&gt; {<br>            bcrypt.hash(newUser.password, salt, (err, hash) =&gt; {<br>               if (err) throw err;<br>               newUser.password = hash;<br>               newUser<br>                  .save()<br>                  .then(user =&gt; res.json(user))<br>                  .catch(err =&gt;<br>                     console.log({ error: &quot;Error creating a new user&quot; })<br>                  );<br>            });<br>         });<br>      }<br>   });<br>});</pre><p><strong><em>Login Route</em></strong> — We start by validating our login input. If the input is invalid, we return the corresponding error message to the user. Else, we check if the user exists in our database. If the user exists we use bcrypt to compare user password with the hashed password stored in the database. If there is a password mismatch or the user does not exist we send back the error else create a payload (id, username), sign it with the secret key, set the expiry time of the token and send the response to the user. Now, if the user wants to access any private data/route, instead of authenticating the user every time we can simply check if the user’s header request contains the token.</p><pre>router.post(&quot;/login&quot;, (req, res) =&gt; {<br>   const { errors, isValid } = validateLoginInput(req.body);<br>   if (!isValid) {<br>      return res.status(400).json(errors);<br>   }<br>   const { email, password } = req.body;<br>   User.findOne({ email }).then(user =&gt; {<br>      if (!user) {<br>         return res.status(404).json({ email: &quot;Email not found&quot; });<br>      }</pre><pre>bcrypt.compare(password, user.password).then(isMatch =&gt; {<br>         if (isMatch) {<br>            const payload = {<br>               id: user.id,<br>               user_name: user.user_name<br>            };<br>            jwt.sign(payload, SECRET, { expiresIn: 3600 }, (err, token) =&gt; {<br>               if (err) {<br>                  console.log(err);<br>               }<br>               return res.json({<br>                  success: true,<br>                  token: &quot;Bearer &quot; + token<br>               });<br>            });<br>         } else {<br>            return res.status(400).json({ password: &quot;Password Incorrect&quot; });<br>         }<br>      });<br>   });<br>});</pre><pre>module.exports = router;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/899af7d6cc0d0164552eb59257b4467f/href">https://medium.com/media/899af7d6cc0d0164552eb59257b4467f/href</a></iframe><p>But currently, our app does not know about these routes. So, we need to tell our app to use the router object that is exported in <em>users.js</em> for user routes. We do that by defining the associated path with the corresponding router in the ‘<em>server.js</em>’ file. Any route request starting with ‘<em>/api/users/</em>’ will be handled by the user router.</p><pre>app.use(&quot;/api/users/&quot;, require(&quot;./routes/api/users&quot;));</pre><p>We had discussed above that once the user logs in the application, we should not re-authenticate the user for every other request. The user could send the jwt token along with the request for getting access to the resource. We will implement this phase of authenticating the user using <a href="http://www.passportjs.org/packages/passport-jwt/">passport-jwt strategy</a>. Passport.js works with concept of strategies. They are basically middleware functions that a request runs through before getting to the actual route.</p><ul><li>Navigate to middleware, create a file <em>passport.js. </em>Import the required dependencies. The <em>opts </em>object finally contains our jwt token and the secret key. When this object is passed in <em>JwtStrategy, </em>we get <em>jwt_payload </em>in our callback (<em>remember our jwt_payload consist of id and username</em>), we then try to find a user with a matching id field in our database and return either no error and the user object or false if the user was not found.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/017868d3c1fce4f21cf47a1f78488f65/href">https://medium.com/media/017868d3c1fce4f21cf47a1f78488f65/href</a></iframe><p>We need to initialize passport in our <em>server.js</em> file and pass passport as a parameter to the function exported by this file.</p><pre>const passport = require(&quot;passport&quot;);</pre><pre>app.use(passport.initialize());<br>require(&quot;./middleware/passport&quot;)(passport);</pre><ul><li>Now, last thing is to create Post APIs. Open <strong><em>posts.js</em>.</strong> Import the following dependencies</li></ul><pre>const express = require(&quot;express&quot;);<br>const router = express.Router();<br>const Post = require(&quot;../../models/Post&quot;);<br>const passport = require(&quot;passport&quot;);<br>const validatePostInput = require(&quot;../../validation/post&quot;);</pre><p>Now, to authenticate (or to make any route private) add the following middleware code as the middle argument of the function.</p><pre>passport.authenticate(&#39;jwt&#39;, {session:false})</pre><p><strong><em>Fetching Posts</em></strong><em> — </em>The user would be able to reach the actual route only if the user is authenticated. The middleware above returns a user object (null, user) on successful authentication. Here, we have made use of the same object returned from the middleware. <strong><em>req </em></strong>contains the user object that can be used to get the user_name. Since, the username and the author would be same we will populate all the posts posted by that user and return them. The second and third function fetches post corresponding to id and author respectively. The first function is private and the other two functions are public.</p><pre>router.get(<br>   &quot;/&quot;,<br><strong>   passport.authenticate(&quot;jwt&quot;, { session: false })</strong>,<br>   (req, res) =&gt; {<br>      Post.find({ author: <strong>req.user.user_name </strong>})<br>         .then(posts =&gt; res.status(200).json(posts))<br>         .catch(err =&gt;<br>            res<br>               .status(400)<br>               .json({ user: &quot;Error fetching posts of logged in user&quot; })<br>         );<br>   }<br>);</pre><pre>router.get(&quot;/post/:id&quot;, (req, res) =&gt; {<br>   Post.find({ _id: req.params.id })<br>      .then(post =&gt; res.status(200).json(post))<br>      .catch(err =&gt; res.status(400).json({ id: &quot;Error fetching post by id&quot; }));<br>});</pre><pre>router.get(&quot;/author/:author&quot;, (req, res) =&gt; {<br>   Post.find({ author: req.params.author })<br>      .then(posts =&gt; res.status(200).json(posts))<br>      .catch(err =&gt;<br>         res<br>            .status(400)<br>            .json({ author: &quot;Error fetching posts of specific author&quot; })<br>      );<br>});</pre><p>Since create, update, and delete should be user-specific we will keep these APIs private.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1479eff790d581fd897e86835feaf757/href">https://medium.com/media/1479eff790d581fd897e86835feaf757/href</a></iframe><p>We need to associate the route in ‘<em>server.js</em>’ file</p><pre>app.use(&quot;/api/posts/&quot;, require(&quot;./routes/api/posts&quot;));</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7adc7c780aad974f6d3e9de1a8ef8689/href">https://medium.com/media/7adc7c780aad974f6d3e9de1a8ef8689/href</a></iframe><p>If you missed out anything, you can check it here</p><p><a href="https://github.com/rajat-dhoot/bloggy">rajat-dhoot/bloggy</a></p><p><strong>5. Now let’s test our Routes using POSTMAN</strong></p><p><strong><em>Signup Endpoint — </em></strong><em>/api/users/signup</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*xj23uNviXFcgn4DdK2X37w.png" /><figcaption>User Signup</figcaption></figure><p><strong><em>Login Endpoint — </em></strong><em>/api/users/login</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*y1vQpXeW6FuCVL0bY21o4g.png" /><figcaption>User Login</figcaption></figure><p>On successful login, we received a token. Set the authorization token for performing further requests for Post endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zw9ZH5FogDUZV1Tg1is0YQ.png" /><figcaption>Setting Authorization Token</figcaption></figure><p><strong><em>Creating Post — </em></strong><em>/api/posts/create</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcGtrqrfT-LQmLi-VrJuOQ.png" /><figcaption>Creating Post</figcaption></figure><p><strong><em>Edit Post — </em></strong><em>/api/posts/update/:id</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JTAJeT2Dz7Voz2iUMyBl8g.png" /><figcaption>Updating Post</figcaption></figure><p><strong><em>Fetch Post</em></strong> — /api/posts/</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qn-SeRibmQewH-0j6jXCwA.png" /><figcaption>Fetching Posts</figcaption></figure><p><strong><em>Deleting Post — </em></strong><em>/api/posts/delete/:id</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*OdPlRsSUl-_wrIBTXzcSwA.png" /><figcaption>Deleting Post</figcaption></figure><p>There are two more endpoints — fetching post by id and fetching posts by author. These are kept public since the posts should be accessible by everyone in case the author wishes to share his blog with them. You can test them out and test each API for various error conditions.</p><h3><strong>Finally, completed Backend !</strong></h3><p>Hope you would have followed along and understood most of the things till now. If you feel that you haven’t understood something, read about it, try building it on your own again. In the next article we will start building front-end for our application.</p><p><a href="https://medium.com/@rajatdhoot/configuring-frontend-redux-mern-blog-application-part-3-c2bccdc463a5">Configuring Frontend &amp; Redux — MERN Blog Application — Part 3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6b807666b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Components & Containers— MERN Blog Application — Part 4]]></title>
            <link>https://medium.com/@rajatdhoot/components-containers-mern-blog-application-part-4-a3b8d8f2c870?source=rss-54d252ec8593------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3b8d8f2c870</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mern]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Rajat Dhoot]]></dc:creator>
            <pubDate>Thu, 29 Aug 2019 18:31:01 GMT</pubDate>
            <atom:updated>2019-08-30T04:03:08.361Z</atom:updated>
            <content:encoded><![CDATA[<h3>Components &amp; Containers— MERN Blog Application — Part 4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JsClH04ugmN_ZdDNZs1Rkw.gif" /><figcaption>Bloggy — MERN Blog Application</figcaption></figure><p>Before continuing further, make sure you know the basics well. However, if you don’t, you can follow the Part-1 of this article series.</p><ul><li><a href="https://medium.com/@rajatdhoot/learn-build-a-mern-stack-application-in-100-hours-part-1-ee56e3f61979">Learn &amp; Build a MERN Stack Application in 100 hours — Part 1</a></li><li><a href="https://medium.com/@rajatdhoot/building-backend-mern-blog-application-part-2-e6b807666b8">Building Backend - MERN Blog Application - Part 2</a></li><li><a href="https://medium.com/@rajatdhoot/configuring-frontend-redux-mern-blog-application-part-3-c2bccdc463a5">Configuring Frontend &amp; Redux — MERN Blog Application — Part 3</a></li></ul><h3><strong><em>Creating Dumb Components</em></strong></h3><p>The folder structure inside components bears the following skeleton</p><pre>components<br>   | <strong>auth<br>       </strong>| Login.js<br>       | SignUp.js<strong><br>   | form<br>       </strong>| Input.js<br>       | Textarea.js<br>       | Validate.js<br><strong>   | layout<br>      </strong> | Landing.js<br>       | NavigationBar.js<br>       | Progress.js<br>   <strong>| posts<br>       </strong>| Post.js<br>       | ListPost.js<br>       | ViewPost.js<br>       | PostForm.js<br>       | post.scss<br><strong>   | user<br>       </strong>| Blog.js<br>       | blog.scss</pre><p><strong><em>form</em></strong></p><ul><li>It contains three component Input, Textarea, and Validate.</li><li>Navigate to form. Create three files Input.js, Textarea.js, Validate.js</li></ul><p><em>Input </em>— To display an input with error, using react-bootstrap, we need the following skeleton.</p><pre>&lt;Form.Group controlId=&quot;formBasicEmail&quot;&gt;<br>    &lt;Form.Label&gt;Email address&lt;/Form.Label&gt;<br>    &lt;Form.Control type=&quot;email&quot; placeholder=&quot;Enter email&quot; isInvalid=&quot;true&quot;/&gt;<br>    &lt;Form.Control.Feedback type=&quot;invalid&quot;&gt;<br>      Invalid<br>    &lt;/Form.Control.Feedback&gt;<br> &lt;/Form.Group&gt;</pre><p>Obviously <em>isInvalid </em>will not be <em>true </em>always<em>. </em>It should only be true when the form control is invalid. While creating the login/signup form we can either add the entire skeleton every time we use the input box or we can extract out the repeated component logic from there and make a small reusable component out of it. So, I had extracted out this basic skeleton from the Login/SignUp Component.</p><p>Now, we should think what object, or functions do we need to make it work. We need <em>onChange h</em>andler to bind the value, we need <em>onBlur </em>handler to check for error on blur, the input can have different types (email, password, text etc) so we need <em>type</em>, we need <em>placeholder, controlId, label, name, value,</em> whether the control is <em>invalid </em>or not, <em>error message</em> if it is invalid. So, we will just implement the component assuming that we will get all these dependencies from our parent component/container (God) and mention these dependency as a prop. We will create a similar textarea component. We would also create a validate function and export it so that we can use it in our container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2121b30672504824ee1b944c1b569024/href">https://medium.com/media/2121b30672504824ee1b944c1b569024/href</a></iframe><p><strong><em>auth</em></strong></p><ul><li>It contains two components Login and SignUp.</li><li>Navigate to auth. Create two files Login.js and SignUp.js</li></ul><p>Now, since components are just presentational unit(dumb), they don’t have their own logic or data. So, we will implement these component in a similar fashion as we implemented Input Component. First, think what are the functions/object that our dumb component require from its parent. We need onChange, onBlur, onSubmit handler for handling our input. We need a loading flag so that we can disable the submit button when the form is getting submitted. We also need user entered data and errors to bind these values accordingly. In Login Component, we require one additional prop i.e. message. It will contain the success message if the user has registered and empty otherwise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46871368d6676221a7b9cb7666149208/href">https://medium.com/media/46871368d6676221a7b9cb7666149208/href</a></iframe><p><strong><em>layout</em></strong></p><ul><li>It contains the component Landing, NavigationBar, &amp; Progress</li><li>Navigate to layout. Create the files Landing.js, NavigationBar.js, Progress.js.</li></ul><p>Create a landing page yourself and name that file as ‘<em>Landing.js</em>’.</p><p><em>Progress </em><strong><em>—</em></strong><em> </em>Here, we have created a progress with 75% width. We have defined animation for it in the class ‘<em>progressBar</em>’ which is declared in the main styles.scss.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ef6fb3ce319e32aad9810f3946a0931/href">https://medium.com/media/8ef6fb3ce319e32aad9810f3946a0931/href</a></iframe><p><em>NavigationBar </em>— While creating this component we require two props, <em>auth and logoutHandler.</em> If the user is logged in we want to display ‘<em>logout’ </em>in the navbar otherwise ‘<em>login’</em>. We need logoutHandler since we need to handle the event when the user clicks <em>logout </em>button.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83f086f32224ececbdfd081ffa2d2363/href">https://medium.com/media/83f086f32224ececbdfd081ffa2d2363/href</a></iframe><p><strong><em>posts</em></strong></p><p><em>ListPost — </em>This component is used to list down all the posts of a particular user. It receives posts as a prop. It uses Post Component to display the post as a card.</p><p><em>Post — </em>This component is responsible for designing &amp; displaying the individual post as a card.</p><p><em>PostForm </em>— This component is responsible to display the form used for creating or updating posts. Similar to Login Component, we require onChange, onBlur, onSubmit handler and loading as a prop. Here, we also require post as a prop to initialize the input form control value.</p><p><em>ViewPost </em>— It accepts posts as a prop and displays the post. It also contain <em>edit </em>and <em>delete</em> button which should only be displayed if the user is authenticated. So, we require editHandler, deleteHandler and isAuthenticated as a prop.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/723f763cada21dbead1bfef8865004cb/href">https://medium.com/media/723f763cada21dbead1bfef8865004cb/href</a></iframe><p><strong><em>user</em></strong></p><p>It contains just a single component as of now i.e. Blog Component. Blog component is responsible for displaying the list of posts of the logged in user (or the blog’s author). It accepts two props <em>isAuthenticated </em>and <em>posts. </em>The create post button should only be available to the logged in user so we need isAuthenticated as a prop. This component also contains a search bar which can be used to filter/search post. If no posts are found, we display ‘<em>No Posts Found</em>’ after waiting for a second.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24a586f796ab05e7f474e855f7707447/href">https://medium.com/media/24a586f796ab05e7f474e855f7707447/href</a></iframe><h3>Creating Smart Containers</h3><p>The folder structure inside containers bears the following skeleton</p><pre>containers<br>   <strong>|</strong> <strong>auth<br>       </strong>| LoginPage.js<br>       | SignUpPage.js<strong><br>   | layout<br></strong>       | NavBar.js<br>       | ProgressBar.js<br>   <strong>| posts<br>       </strong>| CreatePostPage.js<br>       | UpdatePostPage.js<br>       | ViewPostPage.js<br>   | BlogPage.js</pre><p><strong><em>auth</em></strong></p><p><em>SignUpPage — </em>We will create a local state to keep values in sync with the ones entered by the user. We use onChange handler to achieve this. We validate user input and set errors on blur using onBlur handler. The onSubmit handler calls the registerUser action creator. We have used two useEffect calls in this container. The first one is used to clear the error in case the user switches back to signup page already having errors in the login page. The second one is used for two purpose —</p><ul><li>If the user is already logged in he should not be able to visit the signup page, if the user tries to visit it, he gets redirected to the dashboard</li><li>To update the errors object if any errors is returned from the server side.</li></ul><p><em>LoginPage — </em>Its functionality is almost similar to the SignUpPage except that it also checks for any successful login message stored in localStorage. If it gets one, it updates its local message state to pass it down as a prop and removes it from the localStorage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78bca1dbd7b86a0d00ab04fe66f57fdb/href">https://medium.com/media/78bca1dbd7b86a0d00ab04fe66f57fdb/href</a></iframe><p><strong><em>layout</em></strong></p><p><em>Navbar — </em>It is responsible to pass down isAuthenticated prop and onClick handler which calls logoutUser() action creator.<br>ProgressBar — It is responsible to render ProgressBar if either the user, or the post/posts are loading.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a05b838beaa75132dee77924ef6ef470/href">https://medium.com/media/a05b838beaa75132dee77924ef6ef470/href</a></iframe><p><strong><em>posts</em></strong></p><p><em>ViewPostPage</em> — It fetches the post by id mentioned in the url and pass down the post, isAuthenticated, handleEdit and handleDelete functions. The handleEdit function when invoked redirects the application to update post page. handleDelete function deletes the post and redirects the application to the dashboard.</p><p><em>CreatePostPage </em>— It maintains a local state to keep values entered in the post form in sync with the help of onChange handler. It passes down loading flag, post, onChange, OnBlur, and onSubmit functions.</p><p><em>UpdatePostPage — </em>It is similar to createPostPage except that before rendering the page, it loads the post and updates its local state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dba4066bc6502258a100247600298e01/href">https://medium.com/media/dba4066bc6502258a100247600298e01/href</a></iframe><p><strong><em>BlogPage</em></strong> — If the user is authenticated it fetches the posts by the user else if there is a matching parameter in the url it searches posts for that particular author and pass it down to Blog Component and renders it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4a26f16a35d165810c71f4c121d434e/href">https://medium.com/media/e4a26f16a35d165810c71f4c121d434e/href</a></iframe><p>There are few routes which should only be visible to the authenticated user (create post, update post etc) so we need Private Route for that. We make a different component which accepts component, isAuthenticated as a prop and renders the component and its props only if the user is authenticated otherwise redirects the user to the login page.</p><p>Navigate to <strong><em>utils. </em></strong>Create a file named ‘<em>PrivateRoute.js</em>’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59b22c39592ba13e9b1deb51aea44813/href">https://medium.com/media/59b22c39592ba13e9b1deb51aea44813/href</a></iframe><p>The last thing is to actually display all of these components. So, we use ‘<em>App.js</em>’ to wrap and provide routes to display all these components.</p><ul><li>Initially we check if the token still exists in the localStorage and if it is valid, otherwise we logout the user. This also ensures user to be logged in even if the user refreshes the web page.</li><li>We pass down our store using Provider.</li><li>We use Switch to ensure that only one matching route gets rendered.</li><li>We mention each of our valid routes and map it to their corresponding component/container.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52f6701e06adc6a6a443deee457fcd51/href">https://medium.com/media/52f6701e06adc6a6a443deee457fcd51/href</a></iframe><h3>Our Blog Application is ready</h3><p>Hope you enjoyed and learned something out of these articles. If you have missed out on anything you can re-check it here.</p><p><a href="https://github.com/rajat-dhoot/bloggy">rajat-dhoot/bloggy</a></p><p>You can play around with the deployed version of the application here</p><p><a href="https://makemyblog.herokuapp.com/">Bloggy</a></p><p>I am just a beginner in React, so I might not have followed the best practices. If you find anything wrong, do mention that in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3b8d8f2c870" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring Frontend & Redux — MERN Blog Application — Part 3]]></title>
            <link>https://medium.com/@rajatdhoot/configuring-frontend-redux-mern-blog-application-part-3-c2bccdc463a5?source=rss-54d252ec8593------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2bccdc463a5</guid>
            <category><![CDATA[mern]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[blog]]></category>
            <dc:creator><![CDATA[Rajat Dhoot]]></dc:creator>
            <pubDate>Thu, 29 Aug 2019 18:31:01 GMT</pubDate>
            <atom:updated>2019-08-29T18:31:01.325Z</atom:updated>
            <content:encoded><![CDATA[<h3>Configuring Frontend &amp; Redux — MERN Blog Application — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JsClH04ugmN_ZdDNZs1Rkw.gif" /><figcaption>Bloggy — MERN Blog Application</figcaption></figure><p>Before continuing further, make sure you know the basics well. However, if you don’t, you can follow the Part-1 of this article series.</p><ul><li><a href="https://medium.com/@rajatdhoot/learn-build-a-mern-stack-application-in-100-hours-part-1-ee56e3f61979">Learn &amp; Build a MERN Stack Application in 100 hours — Part 1</a></li><li><a href="https://medium.com/@rajatdhoot/building-backend-mern-blog-application-part-2-e6b807666b8">Building Backend - MERN Blog Application - Part 2</a></li></ul><ol><li><strong>Configuration</strong></li></ol><ul><li>Now, we are required to run both server as well as client. To run both of these together we will use the package concurrently. Edit the ‘<strong><em>script</em></strong><em>’ </em>object in the <strong><em>package.json</em></strong> file to match the following:</li></ul><pre>&quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node server.js&quot;,<br>    &quot;server&quot;: &quot;nodemon server.js&quot;,<br>    &quot;client&quot;: &quot;npm start --prefix client&quot;,<br>    &quot;dev&quot;: &quot;concurrently \&quot;npm run server\&quot; \&quot;npm run client\&quot;&quot;<br>  },</pre><p>Later, we will use <strong>npm run dev </strong>to run both of these server together.</p><ul><li>Let’s first create a directory named ‘<strong><em>client</em></strong>’. This directory will be the root directory for our entire frontend code. <strong><em>create-react-app</em></strong><em> </em>is the utility which we will use to create a boilerplate template for our application.</li></ul><pre>mkdir client<br>cd client<br>npm i -g create-react-app  // to install create-react-app globally<br>create-react-app .</pre><ul><li>Let’s install the required dependency using npm</li></ul><pre>npm i react-redux react-bootstrap bootstrap node-sass redux redux-thunk axios jwt-decode react-router-dom</pre><ul><li>Currently we need to add the entire address while making an API request. However, the host name always remain the same so we can extract that and add it as a <a href="https://create-react-app.dev/docs/proxying-api-requests-in-development">proxy </a>in our client’s <em>package.json</em> file.</li></ul><pre>&quot;proxy&quot;: &quot;http://localhost:5000&quot;</pre><p><em>Before adding proxy</em></p><pre>axios.get(&#39;http://localhost:5000/api/posts/&#39;)</pre><p><em>After adding proxy</em></p><pre>axios.get(&#39;/api/posts/&#39;)</pre><ul><li>Move to the app root folder and run <strong>npm run dev<em>. </em></strong>Navigate to localhost:3000 to view react starter template.</li><li>Navigate to public folder. To include <a href="https://react-bootstrap.github.io/getting-started/introduction/">bootstrap </a>stylesheet add the following in <em>index.html</em> file just before the closing head tag. Update the title to ‘<em>Blog App</em>’.</li></ul><pre>&lt;link <em>rel</em>=&quot;stylesheet&quot; <em>href</em>=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css&quot; <em>integrity</em>=&quot;sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T&quot; <em>crossorigin</em>=&quot;anonymous&quot;/&gt;</pre><ul><li>Now go ahead and delete everything from App Component. It should just render a div element. Delete App.css, index.css, App.test.js, logo.svg and if any file imports them remove that declaration.</li></ul><pre><em>import</em> React <em>from</em> &quot;react&quot;;</pre><pre>function App() {<br>   <em>return</em> &lt;div /&gt;;<br>}</pre><pre><em>export</em> <em>default</em> App;</pre><p>Few shortcuts that you should use frequently while creating components</p><pre>imr - import React from &#39;react&#39;<br>impt - <em>import</em> PropTypes <em>from</em> &#39;prop-types&#39;;<br>sfc - Stateless Function Component<br>imrc - import React, {Component} from &#39;react&#39;<br>cc - Class Component<br>ccc - Class Component with Constructor</pre><p>In this project, I have used only Stateless Functional Components (no Class Component). You can however build the same using Class Components. The project directory inside <em>client/src </em>folder bears the following skeleton</p><pre>- src<br><strong>    |</strong> <strong>actions</strong><br><strong>    |</strong> <strong>components<br>    | containers<br>    | reducers<br>    | sass<br>    | utils<br>    | </strong>App.js<br>    | index.js<br>    | serviceWorker.js</pre><p>Let’s work them out one by one.</p><h4>sass</h4><ul><li>Why do we need <a href="https://www.mugo.ca/blog/7-benefits-of-using-SASS-over-conventional-CSS">sass</a>?</li><li>Navigate to the <em>sass</em> folder.</li><li>Create ‘<em>styles.scss</em>’ and import it (as you import css file) in index.js</li><li>Create two partials <em>_variables.scss</em> and <em>_mixins.scss.</em></li><li>You could copy these from below or create/customize your own style.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30a95be3ebbf57e39a8546f7babcf027/href">https://medium.com/media/30a95be3ebbf57e39a8546f7babcf027/href</a></iframe><p><strong><em>utils</em></strong></p><ul><li>Navigate to utils. Create a file named ‘<em>setAuthToken.js</em>’</li><li>We create this utility to set Authorization Token in axios header after the user logs in and remove it if the user logs out. It is done so that we can make an API call without having to worry about authorization token every time we make an API request.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba893bc3208b18f060bf2d3c9793fe8f/href">https://medium.com/media/ba893bc3208b18f060bf2d3c9793fe8f/href</a></iframe><ul><li>Create a file named ‘<em>getFormattedDate.js’. </em>We have created this file to format the date in MMM DD, YYYY (August 29, 2019)format.</li></ul><pre>const getFormattedDate = date =&gt; {<br>   return new Date(Date.parse(date)).toLocaleDateString(&quot;en-US&quot;, {<br>      dateStyle: &quot;long&quot;<br>   });<br>};</pre><pre>export default getFormattedDate;</pre><p><strong><em>Actions</em></strong></p><p><em>Types </em>— Here, we will first create action types. These includes the common set of actions that we are going to perform in our application. We write all of these in a single file (or multiple), export these action types and import them wherever we need them. It helps us keep naming consistent (less chances of typo/error) and gives us one a broad overview about the project features.</p><ul><li>Navigate to the <em>actions </em>folder</li><li>Create ‘<em>types.js’. </em>This is the file where we will define our action types.</li></ul><pre><em>// auth actions<br>export</em> const SET_ERRORS = &quot;SET_ERRORS&quot;;<br><em>export</em> const TOGGLE_USER_LOADING = &quot;TOGGLE_USER_LOADING&quot;;<br><em>export</em> const SET_CURRENT_USER = &quot;SET_CURRENT_USER&quot;;</pre><pre><em>// posts options<br>export</em> const CREATE_POST = &quot;CREATE_POST&quot;;<br><em>export</em> const UPDATE_POST = &quot;UPDATE_POST&quot;;<br><em>export</em> const DELETE_POST = &quot;DELETE_POST&quot;;<br><em>export</em> const GET_POST = &quot;GET_POST&quot;;<br><em>export</em> const TOGGLE_POST_LOADING = &quot;POST_LOADING&quot;;<br><em>export</em> const GET_POSTS = &quot;GET_POSTS&quot;;<br><em>export</em> const RESET_POST = &quot;RESET_POST&quot;;<br><em>export</em> const TOGGLE_POSTS_LOADING = &quot;POSTS_LOADING&quot;;</pre><p><em>Action Creators </em>— Why do we need <a href="https://daveceddia.com/redux-action-creators/">action creators</a>? We will use <a href="https://github.com/reduxjs/redux-thunk#motivation">redux-thunk</a> to create our authentication and post action creators. Why do we need <a href="https://medium.com/fullstack-academy/thunks-in-redux-the-basics-85e538a3fe60">Redux-thunk</a>?</p><p><strong><em>AuthActions</em></strong></p><p><em>User Signup Action</em> — We accept userData and history as parameters. We make an API call to register user sending userData, if the registration is successful we set a message ‘<em>successfully registered </em>’and redirect the user to login page. We have used toggleUserLoading in order to disable button and show loading progress bar till we receive a response from the server.</p><p><em>User Login Action — </em>It accepts userData as the parameter. We make an API call to the login endpoint sending the userData. If the authentication is successful we receive a jwt-token, we store it in a localStorage so that it stays there until we remove it (on user logout/token expires), we set the authToken so that any further API request have the token in its header. Next, we decode the token and set the current user (id, username). We also reset the posts before loading the new users session.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdb6dd6f2088f04d457bad1092666fdd/href">https://medium.com/media/fdb6dd6f2088f04d457bad1092666fdd/href</a></iframe><p><strong><em>Post Actions</em></strong></p><p><em>Create Post </em>— It accepts post data and history as parameter. We make an API call to create a new post. If the post is created we get the post response back. We then dispatch an action to add this post to the user’s current posts. After the post is created, the user is redirected to the dashboard.</p><p><em>Get Post </em>— We have made three different API request for fetching the post.</p><p><em>getPosts</em>() — This request is made for fetching posts when the user is logged in.</p><p><em>getPostsByAuthor() — </em>This request is made for fetching all posts specific to the author when the user enters the url ‘hostname:port/blog/author_name’</p><p><em>getPostById()</em> — This request is made for fetching the individual post.</p><p>Description of <em>Update Post </em>and <em>Delete Post </em>are similar to the ones mentioned above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0f4497c13d16518413dd8deb2b7e0d4/href">https://medium.com/media/d0f4497c13d16518413dd8deb2b7e0d4/href</a></iframe><p><a href="https://redux.js.org/basics/reducers"><strong><em>Reducers</em></strong></a></p><ul><li>Navigate to <em>reducers. </em>Create four files <em>authReducers.js, postReducers.js, errorReducers.js, index.js</em>.</li><li>Remember in our authActions we had dispatched setCurrentUser action two times — when the user logins (sending userdata) and when the user logouts (sending empty object). Now, the actions that we dispatched in authActions are handled by authReducer. It sets the user object if we send a user (or non-empty) object. It also toggles user loading.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aaacdd5d882c6ce3e85edcbb39e1c21/href">https://medium.com/media/1aaacdd5d882c6ce3e85edcbb39e1c21/href</a></iframe><ul><li>In our postReducer, we handle actions that were dispatched in postActions. We load all the user’s posts in an array. When a new post is created, we add that post to the user’s posts array. When user request a specific post we add it in post object. When update request is made we filter out the post that is updated and push the new post object that we received as a response from the server after updating the post. When deleting the post we simply filter out that post from user’s array.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44afa786e71f3329b8683a01227926f8/href">https://medium.com/media/44afa786e71f3329b8683a01227926f8/href</a></iframe><p><em>Error Reducer — </em>It returns the payload sent by the errorAction.</p><pre>import { SET_ERRORS } from &quot;../actions/types&quot;;</pre><pre>const initialState = {};</pre><pre>export default function(state = initialState, action) {<br>   switch (action.type) {<br>      case SET_ERRORS:<br>         return action.payload;<br>      default:<br>         return state;<br>   }<br>}</pre><p>Create a file ‘<em>index.js</em>’. We will combine all three reducer in this file and export it. This final object will act as a rootReducer for our application.</p><pre>import { combineReducers } from &quot;redux&quot;;<br>import authReducer from &quot;./authReducers&quot;;<br>import errorReducer from &quot;./errorReducers&quot;;<br>import postReducer from &quot;./postReducer&quot;;</pre><pre>export default combineReducers({<br>   auth: authReducer,<br>   post: postReducer,<br>   errors: errorReducer<br>});</pre><p>Let’s now create our store. In the src folder, create a file named ‘<em>store.js</em>’. We will export this store, import it in ‘<em>App.js’ </em>and pass it to the entire application using Provider.</p><pre>import { createStore, applyMiddleware } from &quot;redux&quot;;<br>import thunk from &quot;redux-thunk&quot;;<br>import rootReducer from &quot;./reducers&quot;;</pre><pre>const initialState = {};<br>const middleware = [thunk];</pre><pre>const store = createStore(<br>   rootReducer,<br>   initialState,<br>   applyMiddleware(...middleware)<br>);</pre><pre>export default store;</pre><p>For debugging purpose, you should use <a href="https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en">Redux Dev Tools</a>. Since, now we wish to use multiple middleware we would have to wrap them using compose.</p><pre>import { createStore, applyMiddleware, compose } from &quot;redux&quot;;<br>import thunk from &quot;redux-thunk&quot;;<br>import rootReducer from &quot;./reducers&quot;;</pre><pre>const initialState = {};<br>const middleware = [thunk];</pre><pre>const store = createStore(<br>   rootReducer,<br>   initialState,<br>   compose(<br>    applyMiddleware(...middleware),<br>    window.__REDUX_DEVTOOLS_EXTENSION__&amp;&amp;  window.__REDUX_DEVTOOLS_EXTENSION__()));</pre><pre>export default store;</pre><p>If you wish to deploy this application, you would have to revert back to the initial code for ‘<em>store.js’</em>.</p><h3><strong>That’s it for now</strong></h3><p>In the next article we will create dumb components and smart containers. We will then wrap up our code and complete the blog application.</p><p><a href="https://medium.com/@rajatdhoot/components-containers-mern-blog-application-part-4-a3b8d8f2c870">Components &amp; Containers— MERN Blog Application — Part 4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2bccdc463a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn & Build a MERN Stack Application in 100 hours — Part 1]]></title>
            <link>https://medium.com/@rajatdhoot/learn-build-a-mern-stack-application-in-100-hours-part-1-ee56e3f61979?source=rss-54d252ec8593------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee56e3f61979</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mern]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Rajat Dhoot]]></dc:creator>
            <pubDate>Thu, 29 Aug 2019 18:31:01 GMT</pubDate>
            <atom:updated>2019-08-29T18:31:01.178Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn &amp; Build a MERN Stack Application in 100 hours — Part 1</h3><p>By the end of the series of these articles, one should be able to build a blogging application as mentioned below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JsClH04ugmN_ZdDNZs1Rkw.gif" /><figcaption>Bloggy — MERN Blog Application</figcaption></figure><p>We would utilize the initial 50 hours to learn and practice the required concepts and the next 50 hours to build the entire application. I would share the roadmap and the resources that I found helpful in learning these concepts.</p><h4>Prerequisites -</h4><p><a href="https://www.w3schools.com/html/default.asp">HTML</a>, <a href="https://css-tricks.com/">CSS</a>, <a href="https://www.youtube.com/watch?v=3K9X8uDzp2Q&amp;list=PLwoh6bBAszPrVpAyMk1SVvYgGCj-wFweb">SASS</a>, <a href="https://getbootstrap.com/docs/4.3/getting-started/introduction/">Bootstrap</a>, <a href="https://try.github.io/">Git</a>, <a href="https://www.youtube.com/watch?v=W6NZfCO5SIk&amp;list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax">JavaScript</a><br>Try creating a basic landing page using these technologies before proceeding further in this tutorial.</p><h3>MERN (Mongo, Express, React, Node)</h3><p><strong>MongoDB </strong><em>— Estimated Required Time — </em><strong><em>5 </em></strong><em>hours<br></em>Watch the video <a href="https://www.youtube.com/watch?v=tXoTd7TH9K8">tutorial</a>, read and practice <a href="https://docs.mongodb.com/manual/crud/">CRUD </a>operations. You could read <a href="https://docs.mongodb.com/manual/aggregation/">aggregation </a>and <a href="https://docs.mongodb.com/manual/indexes/">indexes</a> as well from the official documentation or skip them as of now. Learn them when you need them.</p><p><strong>Node.js — Express.js</strong> — Estimated Required Time — <strong><em>10 </em></strong><em>hours<br></em>Node.js — <a href="https://www.youtube.com/watch?v=TlB_eWDSMt4">Introductory Video</a>. We would mainly work on Express.js so introductory knowledge is sufficient. However, if you wish to strengthen your fundamental you could practice it <a href="https://www.codecademy.com/learn/learn-node-js">here</a>.</p><p>Express.js — <a href="https://www.youtube.com/watch?v=pKd0Rpw7O48">Introductory Video</a>. Read the following documentation :<br><a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Introduction</a>, <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Using a Database(mongoose)</a>, <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Routes &amp; Controllers</a></p><p><a href="https://www.codecademy.com/learn/asynchronous-javascript">Learn Asynchronous JavaScript</a> — (Callbacks, Promises, <a href="https://alligator.io/js/async-functions/">Async-Await</a>, API requests)</p><p>Try creating a server, connect it with a database, write your APIs, install <a href="https://www.getpostman.com/products">POSTMAN</a> and perform CRUD operations on your APIs.</p><p><strong>React.js</strong> — Estimated Required Time — <strong><em>35 </em></strong><em>hours</em><br>Video Tutorials — <a href="https://www.youtube.com/watch?v=Ke90Tje7VS0">Introduction</a>, <a href="https://www.youtube.com/watch?v=QFaFIcGhPoM&amp;list=PLC3y8-rFHvwgg3vaYJgHGnModB54rxOk3">In-Depth Tutorial</a><br>Don’t worry if you don’t understand all of it, understand the main concepts and go along. Try out the <a href="https://reactjs.org/tutorial/tutorial.html">tutorial </a>exercise mentioned on React official website.</p><p>Read — <a href="https://reactjs.org/docs/hello-world.html">Main Concepts</a> (try out <a href="https://reactjs.org/docs/thinking-in-react.html">Thinking in React</a>), <a href="https://reactjs.org/docs/higher-order-components.html">HOC</a>, <a href="https://reactjs.org/docs/hooks-intro.html">React Hooks</a></p><p>Redux — What is <a href="https://www.youtube.com/watch?v=3sjMRS1gJys">Redux</a>? Now, you probably know what redux is. So, for learning it further follow this <a href="https://github.com/tayiorbeii/egghead.io_redux_course_notes/blob/master/01-Intro_and_3_Principles_of_Redux.md">tutorial </a>(Todo-app)and implement alongside. You could also refer to the <a href="https://redux.js.org/basics/example">code </a>mentioned on the official Redux website.</p><p>Next read about <a href="https://medium.com/fullstack-academy/thunks-in-redux-the-basics-85e538a3fe60">Redux-thunk</a>. For understanding it better, you could also watch this <a href="https://www.youtube.com/watch?v=93p3LxR9xfM">tutorial</a>.</p><p><a href="https://reacttraining.com/react-router/web/guides/quick-start">React-Router</a> — <a href="https://css-tricks.com/react-router-4/">Introduction</a>, <a href="https://tylermcginnis.com/react-router-protected-routes-authentication/">Protected Routes</a><br><a href="https://www.freecodecamp.org/news/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56/">Handling ‘this’ keyword</a>, <a href="https://blog.benestudio.co/5-ways-to-connect-redux-actions-3f56af4009c8">connect() redux action</a></p><p>If you are looking out for a tutorial to build a complete MERN Stack Application here are a few of them: <a href="https://www.youtube.com/watch?v=5oiXG9f6GO0&amp;list=PLuNEz8XtB51K-x3bwCC9uNM_cxXaiCcRY">Tutorial 1</a>, <a href="https://www.youtube.com/watch?v=PBTYxXADG_k&amp;list=PLillGF-RfqbbiTGgA77tGO426V3hRF9iE&amp;index=1">Tutorial 2</a>. But you wouldn’t require them as we would build a blog application together. You could always switch back and refer them if needed.</p><p>Technologies used in our Project —</p><ul><li>FrontEnd: <a href="https://reactjs.org/">React.js</a>, <a href="https://react-redux.js.org/">React-Redux</a>, (<a href="https://www.youtube.com/watch?v=3sjMRS1gJys">Redux?</a>), React Hooks, React-Bootstrap, Redux-thunk, Axios</li><li>Database: <a href="https://www.mongodb.com/">MongoDB</a>, mongoose, <a href="https://cloud.mongodb.com/">MongoDB Atlas</a></li><li>BackEnd: Node.js, Express.js, <a href="http://www.passportjs.org/">Passport.js</a>, JsonWebToken</li></ul><p><a href="https://medium.com/@rajatdhoot/creating-backend-mern-blog-application-part-2-e6b807666b8">Creating Backend — MERN Blog Application — Part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee56e3f61979" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>