<?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 bikash bhandari on Medium]]></title>
        <description><![CDATA[Stories by bikash bhandari on Medium]]></description>
        <link>https://medium.com/@bikash.bhandari05?source=rss-deed02778f10------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KnD0M9wTOPYeNcMC</url>
            <title>Stories by bikash bhandari on Medium</title>
            <link>https://medium.com/@bikash.bhandari05?source=rss-deed02778f10------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 04:44:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bikash.bhandari05/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[Async/Await with practical example]]></title>
            <link>https://articles.wesionary.team/async-await-with-practical-example-ca351f491023?source=rss-deed02778f10------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca351f491023</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[asyncawait]]></category>
            <dc:creator><![CDATA[bikash bhandari]]></dc:creator>
            <pubDate>Sat, 02 May 2020 06:36:11 GMT</pubDate>
            <atom:updated>2020-05-02T06:36:11.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ml53Q1ZvaQNdKhskbli47A.png" /></figure><p>In this article, we will create simple currency converter app and will see how async/await works. We will also know about synchronous and asynchronous programming</p><p><strong>Learning prerequisites</strong></p><ul><li>Be familiar with JavaScript ES6</li><li>Basic knowledge nodejs</li></ul><ol><li><strong>Synchronous request</strong></li></ol><ul><li>Synchronous basically means that you can only execute one thing at a time.</li><li>have to wait for one task to be finish before moving to next one.</li><li>perform one task one at a time</li></ul><p><strong>2. Asynchronous Request</strong></p><ul><li>An asynchronous model allow multiple things to happen at the same time,<br>you don’t have to finish executing the current thing in order to move on to next one. Code execute on background</li><li>in asynchronous programming model, things happen one at a time</li><li>when you call function that performs a long action , it returns only when the action has finished so that it can return the result</li><li>this stops your program for the time that actions take</li></ul><p>Now lets begin with creating simple app. we will use two API as:</p><p>a.<a href="http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&amp;format=1">http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&amp;format=1</a> you can go to .<a href="http://data.fixer.io/">http://data.fixer.io</a> and create account to get your access key</p><p>b.<a href="https://restcountries.eu/rest/v2/currency/$%7BtoCurrency">https://restcountries.eu/rest/v2/currency/${toCurrency</a>} this API gives the list of countries on which currency are convertable</p><p><em>NOTE: you must have nodejs installed in your system.</em></p><p><strong>Project setup</strong></p><p>Create a folder “currency-converter” and locate inside it. Then open the folder using your IDE, i am usig vscode.</p><pre>$ npm init<br>$ yarn add axios<br>//OR using npm <br>$ npm i axios</pre><p>We install axios for our API call. Now lets create index.js file inside our root folder. You can create index.js file directly or using node from your terminal as:</p><pre>$ touch index.js</pre><p>Our folder structure will look like as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUA-5qYQlWaYCtF5epPiJA.png" /></figure><p>We will create 3 functions in index.js<br>1st function:getExchangeRate<br>2nd function:getCountries<br>3rd function:convertCurrency</p><p>In our index.js file lets create function one by one</p><pre>const axios = require(‘axios’)<br>//1st function<br>const getExchangeRate = () =&gt; {<br> const response = axios.get(‘<a href="http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&amp;format=1&#39;">http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&amp;format=1&#39;</a>);<br> console.log(response)</pre><pre>}</pre><pre>getExchangeRate();//function calling</pre><p>We have create getExchnageRate function without using async/await. now you can see we call the API using axios to fetch the data and console.log(response) to see the output. you can run index.js by typing node index.js in your terminal to see the result. You will see the “Pending Promise” and some warning as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlmMpSnKUXKksCX_N_Sb9g.png" /></figure><p>Now lets use async/await in above function and see the output response</p><pre>//in index.js<br>const axios = require(‘axios’)<br>//1st function<br>const getExchangeRate = async () =&gt; {<br> const response = await axios.get(‘<a href="http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&amp;format=1&#39;">http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&amp;format=1&#39;</a>);<br> console.log(response)</pre><pre>}</pre><pre>getExchangeRate();</pre><p>When we use async/await we get actual data as output instead of pending promises.The function doesn’t assign actual data to response variable until all data get fetched, if we don’t use await then response variable will get undefined</p><p><em>NOTE:with async function we can assign all asynchronous fetched response to a variable, we don’t need to use callbacks such as then(), catch()</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNJ_YY-U4x_fO-IKGSrOCw.png" /></figure><p>Now lets write a code that actually convert amount from given “fromCurreny” and “toCurrency”. Our index.js change to</p><pre>//in index.js<br>const axios = require(‘axios’)<br>//1st function<br>const getExchangeRate = async (fromCurrency, toCurrency) =&gt; {<br> const response = await axios.get(‘<a href="http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&amp;format=1&#39;">http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&amp;format=1&#39;</a>);<br> const rates = response.data.rates;<br> const Npr = 1 / rates[fromCurrency]<br> const exchangeRate = Npr * rates[toCurrency];<br> if (isNaN(exchangeRate)) {<br> throw new Error(`Unable to get currency ${fromCurrency} and ${toCurrency} `)<br> }</pre><pre>console.log(exchangeRate)</pre><pre>}</pre><pre>getExchangeRate(‘USD’,’NPR’) //this gives exchange rate from USD doller to Neplease rupee</pre><pre>Type $ node index.js to see the output in your terminal</pre><p>Now lets create second function that gives the list of country name where exchange rates are available</p><pre>//2nd function<br>const getCountries = async (toCurrency) =&gt; {</pre><pre>try {<br> const response = await axios.get(`<a href="https://restcountries.eu/rest/v2/currency/$%7BtoCurrency%7D%60">https://restcountries.eu/rest/v2/currency/${toCurrency}`</a>);<br> const countryNames = response.data.map(country =&gt; { return country.name });<br> return countryNames;</pre><pre>} catch (error) {<br> throw new Error(`Unable to get countries that use ${toCurrency}`)</pre><pre>}<br>}</pre><p>In above function we fetch the list of country where exchange of “toCurrency” are available. We filter the country name only from response using Array Map function.</p><p>And our last function is</p><pre>//3rd function<br>const convertCurrency = async (fromCurrency, toCurrency, amount) =&gt; {<br> const exchangeRate = await getExchangeRate(fromCurrency, toCurrency);<br> const countries = await getCountries(toCurrency);</pre><pre>const convertedAmount = (amount * exchangeRate).toFixed(2);<br> return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spent it in following countries ${countries}`;//1 USD is worth 119 NPR</pre><pre>}</pre><p>The final function “convertCurreny” will gives the converted amount of any two given currency .ie “fromCurrency” and “toCurrency”</p><p>Our final index.js file look like below:</p><pre>//in index.js<br>const axios = require(‘axios’)<br>//1st function<br>const getExchangeRate = async (fromCurrency, toCurrency) =&gt; {<br> const response = await axios.get(‘<a href="http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&amp;format=1&#39;">http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&amp;format=1&#39;</a>);<br> const rates = response.data.rates;<br> const Npr = 1 / rates[fromCurrency]<br> const exchangeRate = Npr * rates[toCurrency];<br> if (isNaN(exchangeRate)) {<br> throw new Error(`Unable to get currency ${fromCurrency} and ${toCurrency} `)<br> }</pre><pre>console.log(exchangeRate)<br> return exchangeRate;<br>}</pre><pre>//2nd function<br>const getCountries = async (toCurrency) =&gt; {</pre><pre>try {<br> const response = await axios.get(`<a href="https://restcountries.eu/rest/v2/currency/$%7BtoCurrency%7D%60">https://restcountries.eu/rest/v2/currency/${toCurrency}`</a>);<br> const countryNames = response.data.map(country =&gt; { return country.name });<br> return countryNames;</pre><pre>} catch (error) {<br> throw new Error(`Unable to get countries that use ${toCurrency}`)</pre><pre>}</pre><pre>}</pre><pre>const convertCurrency = async (fromCurrency, toCurrency, amount) =&gt; {<br> const exchangeRate = await getExchangeRate(fromCurrency, toCurrency);//this will wait until it get the final result<br> const countries = await getCountries(toCurrency);</pre><pre>const convertedAmount = (amount * exchangeRate).toFixed(2);<br> return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spent it in following countries ${countries}`;//1 USD is worth 119 NPR</pre><pre>}</pre><pre>convertCurrency(‘USD’, ‘EUR’, 1)<br> .then(message =&gt; {<br> console.log(message)<br> }).catch(err =&gt; {<br> console.error(err)<br> })</pre><pre>Type: $ node index.js to see output in your terminal</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca351f491023" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/async-await-with-practical-example-ca351f491023">Async/Await with practical example</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spread and Rest operator in JavaScript]]></title>
            <link>https://articles.wesionary.team/spread-and-rest-operator-in-javascript-db3f15cec185?source=rss-deed02778f10------2</link>
            <guid isPermaLink="false">https://medium.com/p/db3f15cec185</guid>
            <category><![CDATA[rest-operator]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[spread-operator]]></category>
            <dc:creator><![CDATA[bikash bhandari]]></dc:creator>
            <pubDate>Wed, 25 Mar 2020 08:07:41 GMT</pubDate>
            <atom:updated>2020-03-25T08:07:41.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*hY3Cg_EXNnEllJt4BN1hAQ.png" /></figure><p>In this articles, i will explain about spread and rest operator in javascript by examples.</p><p><strong>Spread Operator:S</strong>pread syntax allow an iteratable such as an array expression or string to be expanded in a place where zero or more elements are expected<br>or an object expression to be expanded where zero or more key-value pairs are expected. <em>Syntax: …geek</em></p><p>Example 1:</p><pre>&lt;script&gt;<br> let a=[10,20,30];<br> let b=a;<br> a[0]=50;<br> console.log(‘value of a is ‘,a)//OUTPUT: [50,20,30]<br> console.log(‘value of b is ‘,b)//OUTPUT: [50,20,30]<br>&lt;/script&gt;</pre><p>In above code we declare value of ‘a’ as array and we assign value of ‘a’ to ‘b’ which copies value of array ‘a’ to ‘b’ and we see the result<br>as both ‘a’ and ‘b’ has same value.</p><p>but when we change the value of first index of array ‘a’ as a[0]=50 then we see the value of ‘b’ also changes. this is because in javascript, array is reference type i.e it copies reference not value</p><p>this causes problem because when we change the value of element inside array ‘a’ then the value of element of ‘b’ also change.</p><p>so to get rid from such problem,we use spread operator here..it copies data by value not by reference</p><pre>Example2.<br> &lt;script&gt;<br> let a=[10,20,30];<br> let b=[…a]<br> a[0]=50;<br> console.log(‘value of a is ‘,a)//OUTPUT: [50,20,30]<br> console.log(‘value of b is ‘,b)OUTPUT: [10,20,30]<br>&lt;/script&gt;</pre><p>From above Example2,we see when we use sperad operator to copy the value, the change in array ‘a’ doesn’t effect ‘b’</p><p>We can merged or add more data using spread operator as:</p><pre>Example3:<br> &lt;script&gt;<br> let a=[10,20,30];<br> let b=[…a,40,50,60]//adding new data to array ‘b’<br> console.log(‘value of a is ‘,a)//OUTPUT: [10,20,30]<br> console.log(‘value of b is ‘,b)//OUTPUT: [10,20,30,40,50,60]</pre><pre>&lt;/script&gt;</pre><p>Similary we can add new data before or after to spread operator as below:</p><pre>Example4:<br> &lt;script&gt;<br> let a=[10,20,30];<br> let b=[5,6,…a,40,50,60]//adding data before and after spread   operator<br> console.log(‘value of a is ‘,a)//OUTPUT: [10,20,30]<br> console.log(‘value of b is ‘,b)//OUTPUT: [5,6,10,20,30,40,50,60]</pre><pre>&lt;/script&gt;</pre><pre>Example5: Suppose ‘a’ &amp; ‘b’ are two array then we can assign value of ‘a’ and ‘b’ to ‘c’ as below<br> &lt;script&gt;</pre><pre>let a=[10,20,30];<br> let b=[40,50,60];<br> let c=[…a,…b]//c gets value of both a and b</pre><pre>console.log(‘value of a is ‘,a)<br> console.log(‘value of b is ‘,b)<br> console.log(‘value of c is ‘,c)//OUTPUT: [10,20,30,40,50,60]<br>&lt;/script&gt;</pre><p><strong>Spread operator in object:T</strong>he object is also reference type in javascript</p><pre>Example6:<br>&lt;script&gt;</pre><pre>let a={name:’bikash’,profession:’programmer’}<br> let b=a<br> a.name=”padam”;<br> console.log(‘value of a is ‘,a)<br> console.log(‘value of b is ‘,b)<br> &lt;/script&gt;</pre><p>In above Example6, the value of object ‘a’ is assign to ‘b’ as by reference and when we change the value of a.name=”padam” then it also change the value of b object , so to get rid from this we use spread operator</p><pre>Example 7.<br>&lt;script&gt;</pre><pre>let a={name:’bikash’,professional:’programmer’}<br> let b={…a}<br> a.name=”padam”;<br> console.log(‘value of a is ‘,a)<br> console.log(‘value of b is ‘,b)</pre><pre>&lt;/script&gt;</pre><pre>here we can see any change in value of ‘a’ object doesn’t effect in ‘b’</pre><pre>we can add new value to object ‘b’ as <br>Example 8:<br>&lt;script&gt;</pre><pre>let a={name:’bikash’,professional:’programmer’}<br>let b={…a,age:28,height:’5feet 10 inch’}<br></pre><pre>console.log(‘value of a is ‘,a)<br> console.log(‘value of b is ‘,b)</pre><pre>&lt;/script&gt;</pre><p><strong>Rest Operator: </strong>Rest syntax looks exactly like spread syntax, but is used for destructuring arrays and objects.Rest syntax is the opposite of spread syntax. Spread syntax “expands” an array into its elements, while rest syntax collects multiple elements and “condenses” them into a single element.It allow to represent an indefinite number of arguments as an array. <em>Syntax: …rest</em></p><p><strong>NOTE:</strong><em>The rest parameter must be the last parameter to a function, we cannot set rest parameter before or in between to any parameter to a function. …rest here you can set any variable name in name ‘rest’</em></p><pre>eg.<br>function test(param1,paramt2,…rest)<br>{<br>//this is correct<br>}</pre><pre>function test(param1,paramt2,…rest,param3)<br>{<br>//this is wrong<br>}</pre><pre>Example 9: Function with simple parameter<br>&lt;script&gt;</pre><pre>function display(a)<br> {<br> document.write(a)<br> }</pre><pre>display(10)//function call</pre><pre>&lt;/script&gt;</pre><pre>Example 10:Function with rest parameter<br> &lt;script&gt;</pre><pre>function display(a,...rest)<br>      {<br>          document.write(a+&#39;&lt;br/&gt;&#39;)<br>          document.write(rest)<br>      }</pre><pre>      display(10,20,30,40)</pre><pre>&lt;/script&gt;</pre><p>In above Example 10, we see that value 10 is assign to parameter ‘a’ and rest of value 20,30,40 is assign to …rest parameter in form of array</p><p>Accessing the element of rest parameter</p><pre>Example 11:<br> &lt;script&gt;</pre><pre>function display(a,…rest)<br> {<br> document.write(a+’&lt;br/&gt;’)<br> document.write(rest[0]+’&lt;br/&gt;’)<br> document.write(rest[1]+’&lt;br/&gt;’)<br> document.write(rest[2]+’&lt;br/&gt;’)<br> }</pre><pre>display(10,20,30,40)</pre><pre>&lt;/script&gt;</pre><p>From above Example 11, we can see value 10 is assign to parameter ‘a’ and remaining value to rest parameter as array, now we can access value of rest parameter by their index. rest[0] holds value of 20, rest[1] holds value of 30 and so on..</p><p>If we use rest parameter like below then you will get error because rest parameter must be the last parameter to a function</p><pre>Example 12:<br> &lt;script&gt;</pre><pre>function display(a,…rest,c,d)<br> {<br> document.write(a+’&lt;br/&gt;’)<br> document.write(rest[0]+’&lt;br/&gt;’)<br> document.write(rest[1]+’&lt;br/&gt;’)<br> document.write(rest[2]+’&lt;br/&gt;’)<br> }</pre><pre>display(10,20,30,40)</pre><pre>&lt;/script&gt;<br>The script is wrong</pre><h3>Conclusion:</h3><p>Thus we see that, Rest Syntax is the opposite of Spread Syntax. The Spread syntax “expands” an array into its elements, while Rest syntax collects multiple elements and “condenses” them into a single element</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db3f15cec185" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/spread-and-rest-operator-in-javascript-db3f15cec185">Spread and Rest operator in JavaScript</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication System in NodeJs/Express & MongoDB REST APIs]]></title>
            <link>https://articles.wesionary.team/authentication-system-in-nodejs-express-mongodb-rest-apis-4653f8710745?source=rss-deed02778f10------2</link>
            <guid isPermaLink="false">https://medium.com/p/4653f8710745</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[bikash bhandari]]></dc:creator>
            <pubDate>Thu, 19 Mar 2020 09:12:04 GMT</pubDate>
            <atom:updated>2020-03-19T09:12:04.380Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*M10QaO1mZCk_jvH2EBNmaQ.jpeg" /></figure><p>In this article, we will create a REST API that will enable us to login and registered user, get authenticated user profile and logout a user from our system. Here we will use Node.js/Express and MongoDB.</p><p><strong>Learning prerequisites</strong></p><ul><li>Be familiar with JavaScript ES6</li><li>Basic knowledge about REST APIs</li><li>Basic knowledge of MongoDB</li></ul><p><strong>Step 1: Installing and Creating a MongoDB database</strong></p><p>Since i am using ubuntu ,so we can install mongoDB as follow</p><pre>$ sudo apt-get install mongodb<br>$ sudo apt update<br>$ sudo service mongodb start(to start mongodb)<br>For mongo Shell type: <br>$ mongo in your terminal<br>$ show dbs (this will show our database that we have in mongoDB)<br>For creating new database type:<br>$ use mydatabasename (this will use mydatabase if not present then will create it)</pre><pre>To print current used database type: <br>$ db (this will show current database)</pre><pre>To insert data inside collection:<br>$ db.collectionName.insert({“name”:”bikash”})//now collection will be created inside your database<br>To show the collections inside database type:<br>$ show collections<br>To show all documents inside collection type: <br>$ db.yourcollectionname.find();</pre><p>Now, for making it easy we will use Robo 3T . It is an open source MongoDb GUI.Download Robo 3T form here <a href="https://robomongo.org/download">https://robomongo.org/download</a></p><p>After downloading Robo 3T either you will get compressed folder , extract it and you will see following folder as shown below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*yVV9gMmWkU6Xm7lEqFLwgQ.png" /></figure><ul><li>&gt;go inside folder and go to bin folder. inside bin folder you will see robo3t and open it<br>-&gt;after you start robo3t you need to create new connection as below image and save it</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xVGOo0zTdhYUBxZv4sZng.png" /></figure><p><strong>Step 2: Setup a file structure for the project</strong></p><p>After you finish database setup, we can go ahead and create our project. Create a folder anywhere on your computer and name it. I’ve named mine sumulya .Go ahead and set up a file structure like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*88UznlWt8kIcyqIgkdkFRA.png" /></figure><p>From the above file structure, you will realize that we have a root folder called “sumulya” and inside it, we have an index.js file which is our main application file and where we shall define our express server. We also have 4 folders inside “sumulya” root folder.<br>a.application :we will create all business logic here. I have created AuthController.js here<br>b.models: This folder will contain all the models and for this project, it will just be the Usermodel. I have created UserMode.js here<br>c.middleware: This folder contains all middleware to secure our app. i have created auth.js inside middleware folder <br>d.helpers: The helpers folder contains all the helper files inside it. I have created a validation.js and error_handler.js here</p><p>For other remaining files we will create it after project initialization</p><p><strong>Step 3: Initializing Project</strong></p><pre>1.Locate to your project root folder and type $ npm init (this will create package.json file)<br>2.npm install -g nodemon <br>$ yarn add bcrypt (for password security)<br>$ yarn add express<br>$ yarn add moment (for date format)<br>$ yarn add dotenv (for environment variable setup) //this allow to get content of .env file to our index.js file<br>$ yarn add jsonwebtoken (for token generate)<br>$ yarn add mongoose (related to mongoDb)<br>-&gt;Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js. <br>-&gt;It manages relationships between data, provides schema validation, and is used to translate between objects in code <br>$ yarn add cookie-parser<br>-&gt;The cookie parser parses cookies and puts the cookie information on req object in the middleware. <br>-&gt;It will also decrypt signed cookies provided you know the secret.<br>$ yarn add body-parser (related to express)<br>-&gt;To handle HTTP POST request in Express.js version 4 and above, you need to install middleware module called body-parser.<br>-&gt;body-parser extract the entire body portion of an incoming request stream and exposes it on req.body.</pre><pre>NOTE:You must have nodejs and yarn installed in your system. You can install yarn globally.</pre><p><strong>Step 4: Define the environment variables</strong></p><p>Before we go to the next step, let’s include an environment file where we shall define our environment variables. <br>In the root folder , on the same level create a .env file.Inside .env file peste this..<br>MONGODB_URL=your mongoDB database url<br>JWT_KEY=your any secrete key here<br>PORT=5000<br>for eg. i am using following setting in .env</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*c7MD77VWHTCP9xOjIIMCMA.png" /></figure><p>Setup your package.json file as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*Cib6HIHdd_-BvfSPbeHAQg.png" /></figure><p><strong>Step 5: Create an express server inside index.js file</strong></p><pre>//in index.js file<br>const app = require(‘express’)();<br>require(‘dotenv’).config();<br>const port = process.env.PORT || 6000;<br>const bodyParser = require(‘body-parser’);<br>const cookieParser = require(‘cookie-parser’);<br>const mongoose = require(‘mongoose’);<br>mongoose.Promise = global.Promise<br>mongoose.connect(process.env.DATABASE, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })<br>app.use(bodyParser.urlencoded({ extended: true }));<br>app.use(bodyParser.json());<br>app.use(cookieParser());</pre><pre>app.listen(port, () =&gt; {<br> console.log(`Server running at here ${port}`);</pre><pre>});</pre><p>Now go to your terminal and type the command $ yarn run dev . You should be see server running on port 5000 on your terminal. That means we’ve successfully set up our server.</p><p>Inside models folder we have UserModel.js. we will define user schema here.</p><pre>//in UserModel.js<br>require(‘dotenv’).config();<br>const mongoose = require(‘mongoose’);<br>const bcrypt = require(‘bcrypt’);<br>const jwt = require(‘jsonwebtoken’);<br>const SALT = 10;<br>const userSchema = mongoose.Schema({<br> email: {<br> type: String,<br> required: [true,’The email field is required!’],<br> trim: true,<br> unique: 1<br> },<br> password: {<br> type: String,<br> required: [true,’The password field is required!’],<br> minlength: 5<br> },<br> firstName: {<br> type: String,<br> required: [true,’The first name field is required!’],<br> trim: true,<br> maxlength: 100</pre><pre>},<br> lastName: {<br> type: String,<br> required: [true,’The last name field is required!’],<br> trim: true,<br> maxlength: 100</pre><pre>},<br> token: {<br> type: String<br> }</pre><pre>});</pre><pre>//saving user data<br>userSchema.pre(‘save’, function (next) {<br> var user = this;<br> if (user.isModified(‘password’)) {//checking if password field is available and modified<br> bcrypt.genSalt(SALT, function (err, salt) {<br> if (err) return next(err)<br> bcrypt.hash(user.password, salt, function (err, hash) {<br> if (err) return next(err)<br> user.password = hash;<br> next();</pre><pre>});</pre><pre>});</pre><pre>} else {<br> next();<br> }</pre><pre>});</pre><pre>//for comparing the users entered password with database duing login <br>userSchema.methods.comparePassword = function (candidatePassword, callBack) {<br> bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {<br> if (err) return callBack(err);<br> callBack(null, isMatch);</pre><pre>});</pre><pre>}</pre><pre>//for generating token when loggedin<br>userSchema.methods.generateToken = function (callBack) {<br> var user = this;<br> var token = jwt.sign(user._id.toHexString(), process.env.SECRETE);<br> user.token = token;<br> user.save(function (err, user) {<br> if (err) return callBack(err)<br> callBack(null, user)</pre><pre>});</pre><pre>};</pre><pre>//validating token for auth routes middleware<br>userSchema.statics.findByToken = function (token, callBack) {<br> var user = this;<br> jwt.verify(token, process.env.SECRETE, function (err, decode) {//this decode must give user_id if token is valid .ie decode=user_id<br> <br> user.findOne({ “_id”: decode, “token”: token }, function (err, user) {<br> if (err) return callBack(err);<br> callBack(null, user);<br> });</pre><pre>});</pre><pre>};</pre><pre>const User = mongoose.model(‘User’, userSchema);<br>module.exports = { User }</pre><p>Inside middleware folder we have auth.js file. We will verify the token here</p><pre>//in auth.js<br>const { User } = require(‘../models/UserModel’);<br>const auth = (req, res, next) =&gt; {<br> let token = req.cookies.authToken;<br> <br> User.findByToken(token, (err, user) =&gt; {<br> if (err) throw err;<br> if (!user) return res.json({ isAuth: false, error: true })<br> req.token = token<br> req.user = user;<br> next();</pre><pre>});</pre><pre>}</pre><pre>module.exports = { auth }</pre><p>Inside contoller folder we have AuthController.js , we will write logic for user login, register and logout here</p><pre>//in AuthController.js<br><br>const { User } = require(‘../models/UserModel’);</pre><pre>exports.RegisterUser = async (req, res) =&gt; {<br> const user = new User(req.body);<br> await user.save((err, doc) =&gt; {<br> if (err) {</pre><pre>return res.status(422).json({errors:err})</pre><pre>} else {<br> const userData = {<br> firtsName: doc.firstName,<br> lastName: doc.lastName,<br> email: doc.email,</pre><pre>}<br> return res.status(200).json(<br> {<br> success: true,<br> message: ‘Successfully Signed Up’,<br> userData<br> }<br> )<br> }</pre><pre>});<br>}</pre><pre>exports.LoginUser = (req, res) =&gt; {</pre><pre>User.findOne({ ‘email’: req.body.email }, (err, user) =&gt; {</pre><pre>if (!user) {<br> return res.status(404).json({ success: false, message: ‘User email not found!’ });<br> } else {<br> user.comparePassword(req.body.password, (err, isMatch) =&gt; {<br> console.log(isMatch);<br> //isMatch is eaither true or false<br> if (!isMatch) {<br> return res.status(400).json({ success: false, message: ‘Wrong Password!’ });</pre><pre>} else {<br> user.generateToken((err, user) =&gt; {<br> if (err) {<br> return res.status(400).send({ err });</pre><pre>} else {<br> const data = {<br> userID: user._id,<br> firstName: user.firstName,<br> lastName: user.lastName,<br> email: user.email,<br> token: user.token<br> }<br> //saving token to cookie<br> res.cookie(‘authToken’, user.token).status(200).json(<br> {<br> success: true,<br> message: ‘Successfully Logged In!’,<br> userData: data<br> })</pre><pre>}</pre><pre>});</pre><pre>}</pre><pre>});<br> }</pre><pre>});<br>}</pre><pre>exports.LogoutUser = (req, res) =&gt; {<br> User.findByIdAndUpdate(<br> { _id: req.user._id }<br> , { token: ‘’ },<br> (err) =&gt; {<br> if (err) return res.json({ success: false, err })<br> return res.status(200).send({ success: true, message: ‘Successfully Logged Out!’ });</pre><pre>})</pre><pre>}</pre><pre>//get authenticated user details<br>exports.getUserDetails= (req, res) =&gt; {<br> return res.status(200).json({<br> isAuthenticated: true,<br> firstName: req.user.firstName,<br> lastName: req.user.lastName,<br> email: req.user.email,<br> <br> });</pre><pre>});</pre><pre>//finally in Index.js <br>const app = require(‘express’)();<br>require(‘dotenv’).config();<br>const port = process.env.PORT || 6000;<br>const bodyParser = require(‘body-parser’);<br>const cookieParser = require(‘cookie-parser’);<br>const mongoose = require(‘mongoose’);<br>mongoose.Promise = global.Promise<br>mongoose.connect(process.env.DATABASE, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })<br>app.use(bodyParser.urlencoded({ extended: true }));<br>app.use(bodyParser.json());<br>app.use(cookieParser());</pre><pre>app.listen(port, () =&gt; {<br> console.log(`Server running at here ${port}`);</pre><pre>});</pre><pre>const { auth } = require(‘./middleware/auth’)</pre><pre>const { RegisterUser, LoginUser, LogoutUser,getUserDetails } = require(‘./controller/AuthController’);</pre><pre>app.post(‘/api/users/register’,RegisterUser);<br>app.post(‘/api/users/login’,LoginUser);<br>app.get(‘/api/users/auth’,auth,getUserDetails);<br>app.get(‘/api/users/logout’, auth, LogoutUser);</pre><p>In above routes, we notice that we have passed “auth” in userdetails and logout route. auth is a middleware that allow only authenticated user access this route</p><p><strong>Step 6: Conclusion</strong></p><p>Thus, we can successfully made authentication system using nodejs/express and mongoDb , i hope you’ve been able to learn something from this tutorial. Feel free to any questions after regarding this tutorial.<br>You might have one question that why i have not used helpers folder that contain validation.js . For validation mongoose schema automatically validate our data. But in my next tutorial i will validate the registration and login data using express-validator.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4653f8710745" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/authentication-system-in-nodejs-express-mongodb-rest-apis-4653f8710745">Authentication System in NodeJs/Express &amp; MongoDB REST APIs</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Knowledge On React Hooks]]></title>
            <link>https://articles.wesionary.team/knowledge-on-react-hooks-87f616b58b0c?source=rss-deed02778f10------2</link>
            <guid isPermaLink="false">https://medium.com/p/87f616b58b0c</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[bikash bhandari]]></dc:creator>
            <pubDate>Fri, 21 Feb 2020 11:20:56 GMT</pubDate>
            <atom:updated>2020-02-21T11:20:56.465Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’re going to learn about the Hooks available in react that enables users to create state variables without classes. There are multiple Hooks available in React, we will discuss each hooks here.</p><h3>Introduction</h3><ol><li>React Hooks is the latest addition to React in Version 16.8.0</li><li>React Hooks are functions that let us to use React state and life cycle features from functional components.</li><li>By using react hooks, we can easily manipulate the state of our functional component without needing to convert them into class components.</li><li>Hooks don’t work inside class component</li></ol><p><strong>Why to use hooks?</strong></p><p>Since we are not using class in hooks,we get rid from follwing two problems.<br>Reason 1:<br>a.Understand how ‘this’ keywords works in javascripts<br>b.Remember to bind event handler in class component<br>c.Classess don’t minify very well and make hot reloading unreliable</p><p>Reason 2:<br>a.There is no particular logic to reuse stateful component logic in class component but <br>hooks allowing us to reuse stateful logic without changing component hierarchy</p><p>Types of hooks available in react<br>1.useState()<br>2.useEffect()<br>3.useContext()<br>4.useReducer()<br>5.useCallback()<br>6.useMemo()<br>7.useRef()</p><ol><li><strong>useState() Hook:</strong>The useState() is also known as state hooks that allow us using states within functional component.The useState() hooks helps to store the current value entered in the input and provides us with a method to update the state</li></ol><pre>//Example1 </pre><pre>import React, { useState } from ‘react’;</pre><pre>const MyComponent = () =&gt; {<br> const [value, setValue] = useState(‘’);<br> <br> return &lt;input value={value} onChange={e =&gt; setValue(e.target.value)} /&gt;;<br>};</pre><pre>export default MyComponent;</pre><pre>NOTE:useState() function uses initial value,current value and updating value<br>const [currentValue,UpdatingValue]=useState(initialValue)//array destructuring</pre><pre>//Example2.useState() with previousState</pre><pre>useState with previous state</pre><pre>import React,{useState} from ‘react’</pre><pre>function HooksCounter() {<br> const initialCount=0<br> const [count,setCount]=useState(initialCount)<br> const incrementByFive=()=&gt;<br> {<br> <br> for(let i=0;i&lt;5;i++)<br> {<br> setCount(prevCount=&gt;prevCount+1)</pre><pre>}</pre><pre>}<br> return (<br> &lt;div&gt;<br> Count:{count}<br> &lt;button onClick={()=&gt;setCount(initialCount)}&gt;Reset&lt;/button&gt;<br> &lt;button onClick={()=&gt;setCount(prevValue=&gt;prevValue+1)}&gt;Increase&lt;/button&gt;<br> &lt;button onClick={()=&gt;setCount(prevValue=&gt;prevValue-1)}&gt;Descrease&lt;/button&gt;<br> &lt;button onClick={incrementByFive}&gt;IncreaseFive&lt;/button&gt;<br> <br> &lt;/div&gt;<br> )<br>}</pre><pre>export default HooksCounter</pre><pre>Example3: useState() as Object</pre><pre>import React, { useState } from ‘react’</pre><pre>function HooksCounter() {<br> <br> const [name, setName] = useState({ firstName: ‘’, lastName: ‘’ })</pre><pre>return (<br> &lt;div&gt;<br> &lt;form&gt;<br> <br> &lt;input type=”text” value={name.firstName} onChange={e =&gt; setName({…name,firstName : e.target.value })} /&gt;<br> &lt;input type=”text” value={name.lastName} onChange={e =&gt; setName({…name, lastName: e.target.value })} /&gt;<br> <br> <br> &lt;h2&gt;Your First Name is-: {name.firstName}&lt;/h2&gt;<br> &lt;h2&gt;Your Last Name is-: {name.lastName}&lt;/h2&gt;<br> <br> &lt;/form&gt;</pre><pre>&lt;/div&gt;<br> )<br>}</pre><pre>export default HooksCounter</pre><pre>NOTE:useState doesnot automatically merge and update the object..so we use …name above<br>e =&gt; setName({…name,firstName : e.target.value:<br>…name means copy every property from name object and overide firtsname field with different value</pre><pre>//Example4: useState() as Array</pre><pre>import React, { useState } from ‘react’</pre><pre>function UseStateArray() {<br> const [items, setItems] = useState([])<br> const addItem=()=&gt;{<br> //since states doesn;t automatically merge and update the value so we use … spread operator<br> //this means we make a copy of all the items in array using (…) spread operator and append another object<br> setItems([…items,{<br> id:items.length,<br> value:Math.floor(Math.random()*10)+1<br> }])</pre><pre>}<br> return (<br> &lt;div&gt;<br> &lt;button onClick={addItem}&gt;Add Item&lt;/button&gt;<br> &lt;ul&gt;<br> {items.map(item =&gt; (<br> &lt;li key={item.id}&gt;{item.value}&lt;/li&gt;<br> )</pre><pre>)}<br> &lt;/ul&gt;</pre><pre>&lt;/div&gt;<br> )<br>}</pre><pre>export default UseStateArray</pre><p><strong>2.useEffect() Hook:</strong>The Effect hooks let you perform side effects in functional components e.g., ApiFetching, Subscriptions or Events.It is a close replacement for componentDidMount,componentDidUpdate and componentWillUnmount lifecycle.The above 3 lifecycle method can be handle using useEffect().useEffect() run after every render of component<br>useEffect(()=&gt;{}) takes function as a parameter</p><pre>//Example1:useEffect() for fetching data</pre><pre>import React, { useState, useEffect } from ‘react’<br>import axios from ‘axios’</pre><pre>function DataFetching() {<br> const [posts, setPosts] = useState([])<br> useEffect(() =&gt; {<br> axios.get(‘<a href="https://jsonplaceholder.typicode.com/posts&#39;">https://jsonplaceholder.typicode.com/posts&#39;</a>)<br> .then(res =&gt; {<br> console.log(res)<br> setPosts(res.data)<br> })<br> .catch(error =&gt; {<br> console.log(error)<br> })<br> .finally(() =&gt; { console.log(‘always executed’) })</pre><pre>}, [])//passing empty array here cause component did mount only once <br> return (<br> &lt;div&gt;<br> {<br> posts.map(post =&gt; (<br> &lt;li key={post.id}&gt;ID:{post.id}-:{post.title}&lt;/li&gt;<br> ))<br> }<br> &lt;/div&gt;<br> )<br>}</pre><pre>export default DataFetching</pre><pre>//Example2.useEffect() fetching individual post by passing id</pre><pre>import React, { useState, useEffect } from ‘react’<br>import axios from ‘axios’</pre><pre>function DataFetching() {<br> <br> const [post, setPost] = useState({})<br> const [id, setId] = useState(1)<br> useEffect(() =&gt; {<br> <br> axios.get(`<a href="https://jsonplaceholder.typicode.com/posts/$%7Bid%7D%60">https://jsonplaceholder.typicode.com/posts/${id}`</a>)<br> .then(res =&gt; {<br> console.log(res)<br> setPost(res.data)<br> })<br> .catch(error =&gt; {<br> console.log(error)<br> })<br> .finally(() =&gt; { console.log(‘always executed’) })</pre><pre>}, [id])//componentDidMount called when id changes in input filed .i.e useEffect() will rerender when the “id” changes <br> return (<br> &lt;div&gt;<br> &lt;input typ=”text” value={id} onChange={(e) =&gt; setId(e.target.value)} /&gt;<br> &lt;h3&gt;ID:{post.id}=&gt;Title:{post.title}&lt;/h3&gt;<br> <br> &lt;/div&gt;<br> )<br>}</pre><pre>export default DataFetching</pre><p><strong>3.useContext() Hook:</strong>Context hooks is required to pass data from component to another nested child component without using props<br>-:context provides a way to pass data through the component tree without having to pass props down manually at every level.Context API is basically your center store where you can store your data that you want to access globally in your react application. <br>-:suppose we have 4 component..AppComponent,ComponentC,componentD and componentE<br>-:we want to pass props {username} of AppComponent to ComponentE without passing props then we use context<br>there are 3 steps for context<br>1.create a context const UserContext=React.createContext();<br>2.we need to provide the above context with a value..and provider must wrap the children component<br> &lt;UserContext.Provider value=”username here”&gt;<br> &lt;ComponentC /&gt;<br> &lt;/UserContext.Provider&gt;</p><pre>//in App.js<br>import React from ‘react’;</pre><pre>import ComponentC from ‘./components/ComponentC’;</pre><pre>//context api concept<br>export const UserContext = React.createContext();<br>export const ChannelContext = React.createContext();<br>function App() {<br> return (<br> &lt;div className=”App”&gt;<br> <br> &lt;UserContext.Provider value={‘bikash’}&gt;<br> <br> &lt;ChannelContext.Provider value={“bhandari”}&gt;<br> &lt;ComponentC /&gt;</pre><pre>&lt;/ChannelContext.Provider&gt;</pre><pre>&lt;/UserContext.Provider&gt;</pre><pre>&lt;/div&gt;<br> );<br>}</pre><pre>in ComponentC.js<br>import React from ‘react’<br>import ComponentD from ‘./ComponentD’</pre><pre>function ComponentC() {<br> return (<br> &lt;div&gt;<br> &lt;ComponentD/&gt;<br> <br> &lt;/div&gt;<br> )<br>}</pre><pre>export default ComponentC</pre><pre>in ComponentD.js<br>import React from ‘react’<br>import ComponentE from ‘./ComponentE’</pre><pre>function ComponentD() {<br> return (<br> &lt;div&gt;<br> &lt;ComponentE/&gt;<br> <br> &lt;/div&gt;<br> )<br>}</pre><pre>export default ComponentD</pre><pre>in CompinentE.js<br>import React from ‘react’<br>import {UserContext} from ‘./../App’</pre><pre>function ComponentE() {</pre><pre>return (<br> &lt;div&gt;<br> &lt;UserContext.Consumer&gt;<br> {<br> user=&gt;{<br> return &lt;div&gt;Username is {user}&lt;/div&gt;<br> }<br> }</pre><pre>&lt;/UserContext.Consumer&gt;</pre><pre>&lt;/div&gt;<br> )<br>}</pre><pre>export default ComponentE</pre><pre>export default App;</pre><p>NOTE:the above method of using context is not good so we use context hooks</p><p>in using context hooks.the creating and providing value step is same as above…ie step 1 and 2<br>only consuming at child component is different..ie. in componentE.js</p><pre>in ComponentE.js<br>import React,{useContext} from ‘react’<br>import {UserContext,ChannelContext} from ‘./../App’</pre><pre>function ComponentE() {<br> const user=useContext(UserContext)//it return the value of UserContext<br> const channel=useContext(ChannelContext)</pre><pre>return (<br> &lt;div&gt;<br> <br>&lt;h2&gt;The usename is {user} and channel is {channel}&lt;/h2&gt;</pre><pre>&lt;/div&gt;<br> )<br>}</pre><pre>export default ComponentE</pre><p><strong>4.useReducer() Hook: </strong>useReducer() is a Hook use for state management.It is an alternative to useState(). It is related to reducers in javascript check here <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce</a><br>What’s the difference?<br>-&gt;useState() is built using useReducer()<br>When to use useReducer VS useState<br>useState():<br>-&gt;if you want to manage premitive type like integer,string,boolean then useState() is better option<br>-&gt;if you are updating one or two varaibles then useState() is better<br>-&gt;useState() has simple business logic<br>useReducer():<br>-&gt;if you want to manage object useReducer() is better option<br>-&gt;if you are updating more than two states then useReducer() is better<br>-&gt;useRedcer has complex business logic</p><p>useReducer accepts two parameters as useReducer(reducer,initialValue);<br>newState=reducer(currentState,action)<br>reducer returns pair of values as [newState,dispatch]</p><pre>Example:<br>import React, { useReducer } from ‘react’</pre><pre>const initialState = 0;<br>const reducer = (state, action) =&gt; {<br> switch (action) {<br> case ‘increment’:<br> return state + 1;<br> case ‘decrement’:<br> return state — 1;<br> case ‘reset’:<br> return initialState;<br> default:<br> return state;</pre><pre>}</pre><pre>}</pre><pre>function Reducer() {<br> const [count, dispatch] = useReducer(reducer, initialState);<br> //useRedcure return pair of value [count,dispatch] <br> //dispatch method allow us to execute the code corresponding to perticular action</pre><pre>return (<br> &lt;div&gt;<br> Count-:{count}&lt;br/&gt;<br> {/* we have 3 action here */}<br> &lt;button onClick={()=&gt;dispatch(‘increment’)}&gt;Increment&lt;/button&gt;<br> &lt;button onClick={()=&gt;dispatch(‘decrement’)}&gt;Decrement&lt;/button&gt;<br> &lt;button onClick={()=&gt;dispatch(‘reset’)}&gt;Reset&lt;/button&gt;</pre><pre>&lt;/div&gt;<br> )<br>}</pre><pre>export default Reducer</pre><p><strong>5.useCallback() &amp; useMemo(): </strong>Both hook that will return memoized version of callback function that only changes if one of the dependencies has changed.<br>Why useCallback?<br>It is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders</p><pre>Example:<br>import React, { useState, useCallback } from ‘react’</pre><pre>const Counter = () =&gt; {<br> const [count, setCount] = useState(0)<br> const [otherCounter, setOtherCounter] = useState(0)</pre><pre>const increment = () =&gt; {<br> setCount(count + 1)<br> }<br> const decrement = () =&gt; {<br> setCount(count — 1)<br> }<br> const incrementOtherCounter = () =&gt; {<br> setOtherCounter(otherCounter + 1)<br> }</pre><pre>return (<br> &lt;&gt;<br> Count: {count}<br> &lt;button onClick={increment}&gt;+&lt;/button&gt;<br> &lt;button onClick={decrement}&gt;-&lt;/button&gt;<br> &lt;button onClick={incrementOtherCounter}&gt;incrementOtherCounter&lt;/button&gt;<br> &lt;/&gt;<br> )<br>}</pre><pre>in above,the problem here is that any time the counter is updated, all the 3 functions are re-rendered again. to solve this kind of problems we use useCallback()</pre><pre>import React, { useState, useCallback } from ‘react’</pre><pre>const Counter = () =&gt; {<br> const [count, setCount] = useState(0)<br> const [otherCounter, setOtherCounter] = useState(0)</pre><pre>const increment = useCallback(() =&gt; {<br> setCount(count + 1)<br>}, [count])<br>const decrement = useCallback(() =&gt; {<br> setCount(count — 1)<br>}, [count])<br>const incrementOtherCounter = useCallback(() =&gt; {<br> setOtherCounter(otherCounter + 1)<br>}, [otherCounter])</pre><pre>return (<br> &lt;&gt;<br> Count: {count}<br> &lt;button onClick={increment}&gt;+&lt;/button&gt;<br> &lt;button onClick={decrement}&gt;-&lt;/button&gt;<br> &lt;button onClick={incrementOtherCounter}&gt;incrementOtherCounter&lt;/button&gt;<br> &lt;/&gt;<br> )<br>}</pre><p>Now if you try to click one of the counters, only the functions related to the state that changes are going to be re-rendered.</p><p>useMemo():Memoization is basically an optimization technique which passes a complex function to be memoized or remembered. In React, memoization using useMemo hook optimizes our components, avoiding complex re-rendering when it isn’t changed.</p><pre>memoizedValue = useMemo(() =&gt; computeExpensiveValue(value1, value2), [value1, value2]);</pre><pre>const ItemList = useMemo(<br> () =&gt; <br> listOfItems.map(item =&gt; ({<br> …item,<br> itemProp1: expensiveFunction(props.first),<br> itemProp2: anotherPriceyFunction(props.second) <br> })),<br> [listOfItems]<br>)</pre><h3>Conclusion:</h3><p>Thus from this articles we learned about different types of react hooks and found that useState() is associated with state,useEffect() is associated with side effects,useContext() is associated with context API,<br>useReducer() is associated with reducer function of java script and useMemo() is for memoization.<br>For better optimization of react app ,useCallback() and useMemo() hooks are better to use based on different scenario</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87f616b58b0c" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/knowledge-on-react-hooks-87f616b58b0c">Knowledge On React Hooks</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Functional Components VS Class Components]]></title>
            <link>https://articles.wesionary.team/react-functional-components-vs-class-components-86a2d2821a22?source=rss-deed02778f10------2</link>
            <guid isPermaLink="false">https://medium.com/p/86a2d2821a22</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[react-component-lifecycle]]></category>
            <dc:creator><![CDATA[bikash bhandari]]></dc:creator>
            <pubDate>Wed, 12 Feb 2020 14:24:11 GMT</pubDate>
            <atom:updated>2020-03-23T04:18:32.985Z</atom:updated>
            <content:encoded><![CDATA[<p>From this article, we will learn the differences between functional and class components in React and also i will explain which one you should choose.</p><h3>Introduction to component</h3><p>-&gt;a component represent the part of user interface<br>-&gt;component are reusable and can be use in anywhere in user interface</p><p>There are mainly two components in React:</p><ol><li>Functional Components also known as Stateless component</li><li>Class Component also known as Stateful component</li></ol><p><strong>Functional Component or Stateless Component:</strong></p><ul><li>It is simple javascript functions that simply returns html UI</li><li>It is also called “stateless” components because they simply accept data and display them in some form that is they are mainly responsible for rendering UI.</li><li>It accept properties(props) in function and return html(JSX)</li><li>It gives solution without using state</li><li>There is no render method used in functional components.</li><li>These can be typically defined using arrow functions but can also be created with the regular function keyword.</li></ul><pre>example:<br>//with arrow function<br>import React from “react”;</pre><pre>const Person = (props) =&gt; (<br> &lt;div&gt;<br> &lt;h1&gt;Hello, {props.name}&lt;/h1&gt;<br> &lt;/div&gt;<br>);</pre><pre>export default Person;</pre><pre>//without arrow function</pre><pre>import React from “react”;</pre><pre>function Person(props){</pre><pre>return (<br> &lt;div&gt;<br> &lt;h1&gt;Hello, {props.name}&lt;/h1&gt;<br> &lt;/div&gt;<br>)</pre><pre>};<br> <br>export default Person;</pre><p>Lifecycle method or Lifecycle hooks in functional component</p><p>Component lifecycle method do not exist in functional component,because a functional component is just a plain JavaScript function, we cannot use setState() method inside component. That’s why they also get called functional stateless components. <br>We can use React Hooks in functional component,useEffect() hook can be used to replicate lifecycle behaviour, and useState can be used to store state in a functional component.</p><pre>example:<br>const User = (props) =&gt; {<br> const [values, setValues] = useState({<br> email: “”,<br> password: “”<br> } );</pre><pre>useEffect(() =&gt; {<br> if(!props.fetched) {<br> props.fetchData();<br> }<br> console.log(‘mount it!’);<br> }, []); <br> NOTE:By passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating ` componentDidMount` lifecycle behaviour</pre><pre>return(<br> <br> )<br>}</pre><pre>useEffect can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners. An can be used to replicate the componentWillUnmount behaviour<br>Eg: componentWillUnmount</pre><pre>useEffect(() =&gt; {<br> window.addEventListener(‘unhandledRejection’, handler);<br> return () =&gt; {<br> window.removeEventListener(‘unhandledRejection’, handler);<br> }<br>}, [])</pre><p><strong>Class Component or Stateful Component</strong></p><ul><li>It is regular ES6 classes that extends component class form react library</li><li>Also known as “stateful” components because they implement logic and state.</li><li>It must have render() method returning html</li><li>It has complex UI Logic</li><li>You pass props to class components and access them with this.props</li></ul><pre>example:<br>import React, { Component } from “react”;</pre><pre>class Person extends Component {<br> constructor(props){<br> super(props);<br> this.state = {<br> name: “bikash”;<br> }<br> }<br> <br> render() {<br> return (<br> &lt;div&gt;<br> &lt;h1&gt;Hello {this.state.name}&lt;/h1&gt;<br> &lt;/div&gt;<br> );<br> }<br>}</pre><pre>export default Person;</pre><p>Lifecycle method or Lifecycle hooks in Class Component</p><p>The lifecycle hooks of class component can classified method in 4 phases.</p><ol><li><strong>Mounting():</strong></li></ol><ul><li>when an instance of a component is being created and inserted into the DOM</li><li>it has 4 method constructor(),static getDerivedStateFromProps(),render() and componentDidMount()</li></ul><p>a.constructor(props):<br>-&gt;a special function that will get called whenever a new component is created<br>-&gt;initializing the state binding the event handler<br>-&gt;super(props) that directly overites this.state<br>b.static getDerivedStateFromProps(props,state)<br>-&gt;when the state of the component depends on changes<br>c.render():<br>-&gt;we read props and state and return jsx<br>d.componentDidMount()<br>-&gt;invoked immediately after a component and all its children components have been redered to the DOM</p><p><strong>2.Updating():</strong></p><ul><li>when a component is being re-rendered as a result of chnage to either its props or state</li><li>it has 5 lifecycle static getDerivedStateFromProps(),shouldComponentUpdate(),render(),getSnapshotUpdate() and componentDidupdate()</li></ul><p>a.getDerivedStateFromProps()<br>-&gt;This is the first method that is called when a component gets updated.<br>-&gt;This is still the natural place to set the state object based on the initial props.<br>b.shouldComponentUpdate()<br>-&gt;In this method you can return a Boolean value that specifies whether React should continue with the rendering or not.<br>-&gt;The default value is true.<br>c.getSnapshotBeforeUpdate()<br>-&gt;the getSnapshotBeforeUpdate() method you have access to the props and state before the update, meaning that even after the update, you can check what the values were before the update.<br>-&gt;If the getSnapshotBeforeUpdate() method is present, you should also include the componentDidUpdate() method, otherwise you will get an error.<br>d.componentDidUpdate()<br>-&gt;thee componentDidUpdate() method is called after the component is updated in the DOM.</p><p><strong>3.UnMounting:</strong></p><ul><li>used when component is being removed from the DOM.</li><li>it has 1 lifecycle componentWillUnmount()</li></ul><p><strong>4.Error Handeling:</strong></p><ul><li>when there is an error during rendering</li><li>it has 2 lifecycle static getDerivedStateFromProps() and componentDidCatch</li></ul><p><strong>So why to use functional components insted of class component?</strong></p><p>Benefits you get by using functional components in React:<br>1.Functional component are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks<br>2.It has less code which makes it more readable<br>3.It will get easier to separate container and presentational components because you need to think more about your component’s state if you don’t have access to setState() in your component</p><p><strong>Conclusion:</strong><br>If you are writing a presentational component which doesn’t have its own state or needs to access a lifecycle hook,use functional component as much as possible. For state management you can use class component.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86a2d2821a22" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/react-functional-components-vs-class-components-86a2d2821a22">React Functional Components VS Class Components</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Simple ToDo App with React Typescript]]></title>
            <link>https://articles.wesionary.team/creating-simple-todo-app-with-react-typescript-e569bd072a13?source=rss-deed02778f10------2</link>
            <guid isPermaLink="false">https://medium.com/p/e569bd072a13</guid>
            <category><![CDATA[react-todo-app]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[bikash bhandari]]></dc:creator>
            <pubDate>Sat, 08 Feb 2020 10:10:16 GMT</pubDate>
            <atom:updated>2020-02-10T21:12:37.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nuzfeKL1Cw0-OQGcJYtnhg.png" /></figure><p>In my previous articles, i have explained about typescript basic and how it can be used in javascript <a href="https://medium.com/wesionary-team/what-is-typescript-and-how-it-can-be-used-in-javascript-e4f2a8a7099d">https://medium.com/wesionary-team/what-is-typescript-and-how-it-can-be-used-in-javascript-e4f2a8a7099d</a>. Now in this articles we will learn how to build ToDo list app with React and TypeScripts. This tutorial will teach you building simple react Todo app in professional approach.</p><h3>Environment setup</h3><p>At First ,all you need have installed react with typescript for creating our application ,you can install it using npm or yarn as follow:</p><pre>$ npx create-react-app my-app — template typescript<br># or<br>$ yarn create react-app my-app — template typescript</pre><p>The above command will create starting template for your Todo app name “my-app”.Also we will install one more dependency “shortid” package. The shortId creates short non-sequential url-friendly unique ids.</p><pre> $ npm i shortid <br> $ npm i <a href="http://twitter.com/types/shortid">@types/shortid</a> //for typescript<br>//OR<br> $ yarn add shortid <br> $ yarn add <a href="http://twitter.com/types/shortid">@types/shortid</a> //for typescript</pre><p>Below image is the final structure of our Todo app project. Make your project structure same as i mention below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7M9G6_SC-1ShRf6wT36jgg.png" /></figure><p><strong>Interfaces:</strong><br>At first we will create interfaces for our Todo app. We will use them to define the shape of component props and the Todo object.We will need to create 4 interfaces in interface.ts file<br>1.one for todo (todo object):The todo object will have three properties, id, name, isCompleted.<br>2.one for Todo form:The ToDoForm props contain array of Todo objects and handleTodoCreate method. <br>3.one for Todo list : The ToDoList props will contain handleTodoUpdate, handleTodoRemove, handleTodoComplete<br>4.one for Todo item:The ToDoItem props will contain handleTodoUpdate, handleTodoRemove, handleTodoComplete</p><p>Also we will create 3 files (ToDoForm.tsx,ToDoItem.tsx,ToDoList.tsx) inside our components folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KGO0HRxb3e3SiprHuoFXQ.png" /></figure><p>Now in ToDoItem component,we will import the TodoItemInterface from interface.ts and to use it to type props of this component.</p><pre><br>// in ToDoItem.tsx</pre><pre>import * as React from ‘react’</pre><pre>// Import interfaces</pre><pre>import { TodoItemInterface } from ‘../interface’</pre><pre>// TodoItem component</pre><pre>const ToDoItem = (props: TodoItemInterface) =&gt; {</pre><pre>return (</pre><pre>&lt;div className=’todo-item’&gt;</pre><pre>&lt;div onClick={() =&gt; props.handleTodoComplete(props.todo.id)}&gt;</pre><pre>{props.todo.isCompleted ? (</pre><pre>&lt;span className=”todo-item-checked”&gt;✔&lt;/span&gt;</pre><pre>) : (</pre><pre>&lt;span className=”todo-item-unchecked” /&gt;</pre><pre>)}</pre><pre>&lt;/div&gt;</pre><pre>&lt;div className=”todo-item-input-wrapper”&gt;</pre><pre>&lt;input</pre><pre>value={props.todo.name}</pre><pre>onChange={(event: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; props.handleTodoUpdate(event, props.todo.id)}</pre><pre>/&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div className=”item-remove” onClick={() =&gt; props.handleTodoRemove(props.todo.id)}&gt;</pre><pre>⨯</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>)</pre><pre>}</pre><pre>export default ToDoItem</pre><pre>NOTE: We use React.ChangeEvent&lt;HTMLInputElement&gt;  because we are attaching onChange handler to input element.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8Sn7NAzgmvF0miYR81jfA.png" /></figure><p>In ToDoList component.We will create a handler methods for the ToDoItem that we create above, and array of todo objects through props.<br>We will import TodoListInterface and use it as props of the ToDoList component.</p><pre>//in ToDoList.tsx<br>import * as React from ‘react’</pre><pre>import TodoItem from ‘./ToDoItem’</pre><pre>import { TodoListInterface } from ‘../interface’</pre><pre>const ToDoList = (props: TodoListInterface) =&gt; {<br> return (<br> &lt;div className=”todo-list”&gt;<br> &lt;ul&gt;<br> {props.todos.map((todo) =&gt; (<br> &lt;li key={todo.id}&gt;<br> &lt;TodoItem<br> todo={todo}<br> handleTodoUpdate={props.handleTodoUpdate}<br> handleTodoRemove={props.handleTodoRemove}<br> handleTodoComplete={props.handleTodoComplete}<br> <br> /&gt;<br> &lt;/li&gt;<br> ))}<br> &lt;/ul&gt;<br> &lt;/div&gt;<br> )<br>}<br>export default ToDoList</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_4qIed4WJqzndSThUgiuA.png" /></figure><p>In ToDoForm component we will use useState &amp; useRef React hook.useState hook is to store data passed to the input element, and <br> useRef hook to store reference to this input.<br>Also we will use shortid package here to generate unique id for every new todo. All we need is to call generate() on shortid.</p><pre>//in ToDoForm.tsx<br>import * as React from ‘react’<br>import shortid from ‘shortid’</pre><pre>import {TodoInterface, TodoFormInterface} from ‘../interface’</pre><pre>const ToDoForm = (props: TodoFormInterface) =&gt; {<br> <br> const inputRef = React.useRef&lt;HTMLInputElement&gt;(null)<br> <br> const [values, setValues] = React.useState(‘’)</pre><pre>function handleInputChange(event: React.ChangeEvent&lt;HTMLInputElement&gt;) {<br> <br> setValues(event.target.value)<br> }<br> <br> function handleInputEnter(event: React.KeyboardEvent) {<br> // Check for ‘Enter’ key<br> if (event.key === ‘Enter’) {<br> // Prepare new todo object<br> const newTodo: TodoInterface = {<br> id: shortid.generate(),<br> name: values,<br> isCompleted: false<br> }<br> // Create new todo item<br> props.handleTodoCreate(newTodo)<br> // Reset the input field<br> if (inputRef &amp;&amp; inputRef.current) {<br> inputRef.current.value = ‘’<br> }<br> }<br> }<br> return (<br> &lt;div className=”todo-form”&gt;<br> &lt;input<br> ref={inputRef}<br> type=”text”<br> placeholder=’Enter new todo’<br> onChange={event =&gt; handleInputChange(event)}<br> onKeyPress={event =&gt; handleInputEnter(event)}<br> /&gt;<br> &lt;/div&gt;<br> )<br>}<br>export default ToDoForm</pre><p>Finally we will import all components inside our App.tsx file</p><pre>//in App.tsx <br>import * as React from ‘react’<br>import { render } from ‘react-dom’<br>// Import components<br>import ToDoForm from ‘./components/ToDoForm’<br>import ToDoList from ‘./components/ToDoList’<br>// Import interfaces<br>import { TodoInterface } from ‘./interface’<br>import ‘./style.css’</pre><pre>const App: React.FC = () =&gt; {<br> const [todos, setTodos] = React.useState&lt;TodoInterface[]&gt;([])<br> // Creating new todo item<br> function handleTodoCreate(todo: TodoInterface) {<br> const newTodosState: TodoInterface[] = […todos]<br> newTodosState.push(todo)<br> setTodos(newTodosState)<br> }<br> // Update existing todo item<br> function handleTodoUpdate(event: React.ChangeEvent&lt;HTMLInputElement&gt;, id: string) {<br> <br> const newTodosState: TodoInterface[] = […todos]<br> <br> newTodosState.find((todo: TodoInterface) =&gt; todo.id === id)!.name = event.target.value<br> <br> setTodos(newTodosState)<br> }</pre><pre>// Remove existing todo item<br> function handleTodoRemove(id: string) {<br> <br> const newTodosState: TodoInterface[] = todos.filter((todo: TodoInterface) =&gt; todo.id !== id)<br> <br> setTodos(newTodosState)<br> }</pre><pre>// Check existing todo item as completed<br> function handleTodoComplete(id: string) {<br> <br> const newTodosState: TodoInterface[] = […todos]<br> // Find the correct todo item and update its ‘isCompleted’ key<br> newTodosState.find((todo: TodoInterface) =&gt; todo.id === id)!.isCompleted = !newTodosState.find((todo: TodoInterface) =&gt; todo.id === id)!.isCompleted</pre><pre>setTodos(newTodosState)<br> }</pre><pre>return (<br> &lt;div className=”App”&gt;</pre><pre>&lt;React.Fragment&gt;<br> &lt;h2&gt;My ToDo APP&lt;/h2&gt;<br> &lt;ToDoForm<br> todos={todos}<br> handleTodoCreate={handleTodoCreate}<br> /&gt;<br> &lt;ToDoList<br> todos={todos}<br> handleTodoUpdate={handleTodoUpdate}<br> handleTodoRemove={handleTodoRemove}<br> handleTodoComplete={handleTodoComplete}<br> <br> /&gt;<br> <br> &lt;/React.Fragment&gt;<br> &lt;/div&gt;<br> );<br>}</pre><pre>export default App;</pre><p>For Styling our app</p><pre>html {</pre><pre>box-sizing: border-box;</pre><pre>}</pre><pre>*,</pre><pre>*::before,</pre><pre>*::after {</pre><pre>box-sizing: inherit;</pre><pre>}</pre><pre>#root,</pre><pre>body {</pre><pre>min-height: 100vh;</pre><pre>}</pre><pre>body {</pre><pre>margin: 0;</pre><pre>}</pre><pre>#root,</pre><pre>.todo-list-app {</pre><pre>display: flex;</pre><pre>flex-flow: column nowrap;</pre><pre>}</pre><pre>#root {</pre><pre>align-items: center;</pre><pre>width: 100%;</pre><pre>}</pre><pre>.todo-list-app {</pre><pre>padding-top: 32px;</pre><pre>width: 100%;</pre><pre>max-width: 480px;</pre><pre>}</pre><pre>.todo-form input,</pre><pre>.todo-item {</pre><pre>border: 1px solid #ececec;</pre><pre>}</pre><pre>.todo-form input {</pre><pre>padding: 0 14px;</pre><pre>width: 100%;</pre><pre>height: 48px;</pre><pre>transition: .25s border ease-in-out;</pre><pre>}</pre><pre>.todo-form input:focus {</pre><pre>outline: 0;</pre><pre>border: 1px solid #3498db;</pre><pre>}</pre><pre>/* Todo list styles */</pre><pre>.todo-list ul {</pre><pre>padding: 0;</pre><pre>margin: 0;</pre><pre>}</pre><pre>.todo-list li {</pre><pre>list-style-type: none;</pre><pre>}</pre><pre>/* Todo item styles */</pre><pre>.todo-item {</pre><pre>display: flex;</pre><pre>flex-flow: row nowrap;</pre><pre>align-items: center;</pre><pre>padding: 8px;</pre><pre>}</pre><pre>.todo-form + .todo-list ul .todo-item {</pre><pre>border-top: 0;</pre><pre>}</pre><pre>.todo-item-input-wrapper {</pre><pre>flex-grow: 1;</pre><pre>padding: 0 16px;</pre><pre>}</pre><pre>.todo-item input {</pre><pre>width: 100%;</pre><pre>border: 0;</pre><pre>border-bottom: 1px solid transparent;</pre><pre>transition: .25s border-bottom ease-in-out;</pre><pre>}</pre><pre>.todo-item input:focus {</pre><pre>outline: 0;</pre><pre>border-bottom: 1px solid #3498db;</pre><pre>}</pre><pre>.todo-item .todo-input-error {</pre><pre>border-bottom: 1px solid #e74c3c;</pre><pre>}</pre><pre>.todo-item span {</pre><pre>display: flex;</pre><pre>align-items: center;</pre><pre>justify-content: center;</pre><pre>width: 32px;</pre><pre>height: 32px;</pre><pre>border-radius: 50%;</pre><pre>border: 1px solid #ececec;</pre><pre>transition: .25s all ease-in-out;</pre><pre>}</pre><pre>.todo-item-unchecked:hover {</pre><pre>background: hsla(168, 76%, 42%, .25);</pre><pre>border: 1px solid hsl(168, 76%, 42%, .25);</pre><pre>}</pre><pre>.todo-item-checked {</pre><pre>color: #fff;</pre><pre>background: #1abc9c;</pre><pre>border: 1px solid #1abc9c;</pre><pre>}</pre><pre>.item-remove {</pre><pre>display: flex;</pre><pre>padding-left: 8px;</pre><pre>padding-right: 8px;</pre><pre>font-size: 28px;</pre><pre>cursor: pointer;</pre><pre>line-height: 1;</pre><pre>color: #ececec;</pre><pre>transition: .25s color ease-in-out;</pre><pre>}</pre><pre>.item-remove:hover {</pre><pre>color: #111;</pre><pre>}</pre><h3>Conclusion: We successfully build a simple Todo App with React Hooks and TypeScript</h3><p>You can add more features in this app or you can create any app by implementing this technology you have just learned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e569bd072a13" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/creating-simple-todo-app-with-react-typescript-e569bd072a13">Creating Simple ToDo App with React Typescript</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Typescript and how it can be used in javascript]]></title>
            <link>https://articles.wesionary.team/what-is-typescript-and-how-it-can-be-used-in-javascript-e4f2a8a7099d?source=rss-deed02778f10------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4f2a8a7099d</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[bikash bhandari]]></dc:creator>
            <pubDate>Thu, 06 Feb 2020 08:54:43 GMT</pubDate>
            <atom:updated>2020-02-06T19:33:40.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*o6eQyQMnsJNVTblB7iXj_g.png" /></figure><p>From this article, we will learn what and why typescript is used for development, also we will learn about variable declaration,variables types,functions,classes, and interface in typescript</p><p>What is typescript?<br>1.Typescript is open source programming language from microsoft<br>2.It is a strict syntactical superset of JavaScript,<br>3.Compiles down to plain javascripts</p><p>Why to use typescript?<br>1.TypeScript help catch mistakes early through a type system and to make JavaScript development more efficient.<br>2.TypeScript simplifies our JavaScript code and making it easier to read,understand and debug to the developer.<br>3.TypeScript follows the OOPS concept and with the help of TSC (TypeScript Compiler), we can convert Typescript code (.ts file) to JavaScript (.js file)<br>4.With the help of TypeScript, we can make a huge improvement over plain JavaScript.</p><h3><strong>Environment Setup</strong></h3><p>The first step is download and install nodejs in our system. We can download it from here <a href="https://nodejs.org/en/">https://nodejs.org/en/</a><br>After installing nodejs we can check its version by using following command</p><pre>$ node -v</pre><p>The second step is installing typescript, we will install typescript globally with the help of nodejs using our terminal</p><pre>$ npm install -g typescript</pre><pre>// we can check the version of typescript as<br>$ tsc -v</pre><p>Now create a folder “typescript” and open folder with your IDE, i am using vscode here, lets create our first typescript file “main.ts” inside typescript folder<br>NOTE: .ts is extension for typescript file</p><pre>//inside main.ts we will print our first message <br>let message=”helo my name is bikash”<br>console.log(message);</pre><pre>now we need to complie it to plain javascript, open terminal inside your “typescript” folder and run<br>$ tsc main.ts <br>//or you can simply run $ tsc main , you dont need to write extension of file here</pre><pre>The above command will create a js file “main.js” which contain the transpiled javascript ,inside main.js we can see the “let” declaration is changed to “var” declaration</pre><pre>Now to run the code we don&#39;t really need the browser, we can run it in our terminal with help of node command<br>we will run javascript(js) file here not .ts file<br>$ node main.js</pre><pre>after above command you will see the output “my name is bikash” in your terminal</pre><pre>Now in main.ts file you might notice some error, this happens because the file is treated as script rather than a module.<br>a module has it’s own scope where as script has a global scope.To get rid from that type of error we will export a module in main.ts file and compile main.ts as</pre><pre>$ tsc main.ts</pre><pre>now the change is reflected in main.js file as well<br>“use strict”;<br>exports.__esModule = true;<br>var message = “helo my name is bikash”;<br>console.log(message);</pre><pre>We need to automatically recompiled the typescript file when there is a change using “watch” option <br>$ tsc main — watch</pre><pre>The &quot;watch&quot; will check if there is any change in typescript file and will automatically recompiled and transpiled in to javascript file</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*NS0_7nQaWKQggOZBZjmKuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*wr1Q1wNGUDhTpuFuS3pzLA.png" /></figure><p><strong>Variable Declarations</strong></p><p>Typescript encourages the use of “let” and “const” keyword for variable declaration<br>1.use “let” keyword if your variable changes in your code and not constant</p><p>2.use “const” keyword if your variable never changes below</p><p>3.You can’t re-declare the same variable multiple times with use of “let” and “const” keyword</p><pre>Examples.<br>//in main.ts</pre><pre>let x=20;<br>const y=30;<br>//now again we can’t declare value of x using let<br>let x=50//wrong<br>const y=50;//wrong</pre><pre><br>//again</pre><pre>let x=20;<br>const y=30;</pre><pre>x=30;//we can assign value of x like this<br>y=50;//wrong we can&#39;t assign new value here</pre><pre>“let” keyword can be used without variable initialization <br>let x;<br>x=50;</pre><pre>But “const” must be initialized with some value<br>const y;//wrong<br>y=10;//wrong<br>const y=1;//right</pre><p>VARIABLE TYPES:<br>Lets see some basic types in typescript,the types is assign in variable by appending colon(:) followed by variable<br>a.boolean<br>b.number<br>c.string<br>d.null<br>e.undefined<br>f.Array<br>g.enum<br>h:any</p><pre>//in main.ts<br>let isActive:boolean=true//declaring isActive as boolean<br>isActive=”bikash”//wrong because isActive is of type boolean, we can’t assign string here</pre><pre>let z:number;<br>z=10;//right<br>z=”test”//wrong because z is of type number, we can;t assign string value</pre><pre>let name:string=”bikash”;<br>name=”bhandari”//right<br>name=10//wrong</pre><pre>let n:null=null;<br>let u:undefined=undefined;</pre><pre>let isNew:boolean=null;right<br>let myName:string=undefined;right</pre><pre>//Array types<br> let list1:number[]=[1,2,3..]//list1 is array of number <br> list1=[1,”a”,”b”]//this is wrong because we can only assign number not string<br>//OR<br>let list2:Array&lt;number&gt;=[1,2,3];</pre><pre>let person:[string,number]=[‘bikash’,1];//array of type string and number</pre><pre>//enum type<br>enum Color={Red=5,Blue,Green}<br>let c:Color=Color.green;<br>console.log(c)</pre><pre>//any type<br>let a:any;<br>a=10//right<br>a=”my name”;//right<br>a=true//right</pre><pre>//for assigning multiple type</pre><pre>let multiType:number | boolean<br>multiType=10;<br>multitype=true;</pre><p>FUNCTIONS</p><pre>//examples<br>function add(num1,num2?)//? sign indicate num2 is optional<br>{<br> return num1+num2;<br>}</pre><pre>add(5,’a’)//this gives error so to prevent such issue we defined types in function</pre><pre>function add(num1:number,num2:number):number//return type is number<br>{<br> return num1+num2;<br>}</pre><pre>add(5,6);<br>add(5,’a’)//wrong can’t assign<br>console.log(add(5,6))<br>//OUTPUT:11</pre><p>INTERFACE</p><p>It helps to maintain the code standard and makes code more readable</p><pre>//in main.ts<br>//function without using interface<br>function fullName(person:{firstName:string,lastName:string})<br>{<br>console.log(`${person.firstName} ${person.lastName}`)</pre><pre>}</pre><pre>let p={<br>firstName:’bikash’,<br>lastName:’bhandari’</pre><pre>}</pre><pre>fullName(p)//function calling</pre><pre>in above function it has only two properties firstName and lastName, but imagine a functions that have many properties,it is not good practice to write all of them as parameter. so solution is using interface</pre><pre>//using interface<br>interface Person{<br>firstName:string;<br>lastName:string;<br>address:string;<br>age?:number;//age is optional</pre><pre>}</pre><pre>function fullName(person:Person)<br>{<br>console.log(`Helo ${person.firstName} ${person.lastName} you address is ${person.address}`)</pre><pre>}</pre><pre>let p={<br>firstName:’bikash’,<br>lastName:’bhandari’,<br>address:’kathmandu’,</pre><pre>}</pre><pre>fullName(p)//function calling</pre><p>CLASSES</p><p>In plain javascript there is no concept of classes, to overcome this typescript also support classes</p><pre>//in main.ts<br>class Employee {<br>employeeName:string;</pre><pre>constructor(name:string)<br>{<br> this.employeeName=name;<br>}</pre><pre>display()<br>{</pre><pre>console.log(`Helo ${this.employeeName}`);<br>}</pre><pre>}</pre><pre>let emp1=new Employee(‘bikash’);<br>emp1.display();</pre><p>My next article will be about using typescript in react app and we will build simple Todo app with react typescript</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4f2a8a7099d" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/what-is-typescript-and-how-it-can-be-used-in-javascript-e4f2a8a7099d">What is Typescript and how it can be used in javascript</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to setup authentication in react typescript and redux]]></title>
            <link>https://articles.wesionary.team/how-to-setup-authentication-in-react-typescript-and-redux-6e2dd5616e30?source=rss-deed02778f10------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e2dd5616e30</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[bikash bhandari]]></dc:creator>
            <pubDate>Sun, 02 Feb 2020 10:36:16 GMT</pubDate>
            <atom:updated>2020-02-02T10:56:54.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZMAK4krhSP2oRS-76HFLg.png" /></figure><p>From this tutorial, we will create authentication system by creating private and guest routes with implementation of redux<br>NOTE:For understanding this ,you must have basic knowledge in react redux and its flow</p><p>What is Redux?<br>1.Redux is a state management container for JavaScript applications.<br>2.Redux makes it easy to manage the state of your application,it helps you manage the data you display and how you respond to user actions.<br>3.There are 3 aspects of data that we’d need to manage in our applications:<br>a.Fetching and storing data<br>b.Assigning data to UI elements<br>c.Changing data</p><p>4.There are 3 main parameter in redux<br>a.Actions:Actions are payloads of information that send data from your application to your store. They are the source of information for the store. We can send data to the store using store.dispatch(). <br>b.Reducers:The Reducers specify how our application’s state changes in response to actions that are sent to the store.<br>c.Stores:The Store is the object that bring and combine Actions &amp; Reducers together.The store has the following responsibilities:</p><ul><li>&gt;Holds the application state;<br>-&gt;Allows access to state via getState();<br>-&gt;Allows state to be updated via dispatch(action);<br>-&gt;Registers listeners via subscribe(listener);<br>-&gt;Handles unregistering of listeners via the function returned by subscribe(listener).</li></ul><h3><strong>Environment setup</strong></h3><p>At First ,all you need have installed react with typescript for creating our application , You can install it using npm or yarn using terminal:</p><pre>Step1:$ npx create-react-app my-app — template typescript<br> or<br>yarn create react-app my-app — template typescript</pre><pre>Step2:install redux as follow<br>$ npm install — save redux react-redux redux-thunk</pre><pre>Step3:install axios for api call<br>$ npm install --save axios</pre><pre>Step4:install react-router-dom<br>$ npm install --save react-router-dom</pre><p>5.Now inside your app folder make 3 folder as show in below image<br>-&gt;components//for app component<br>-&gt;redux//for redux stuff<br>-&gt;utils//for extra helper functions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*n9BRIDmYBks8GhE8T33uWQ.png" /></figure><p>Now inside redux folder we will create 2 folders “actions” and “reducers” and will create stores.ts and types.ts file as follow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*yNfjhWJnHBFKpo-v7a3ryA.png" /></figure><pre>//In types.ts we will define constants for user authentication and UI loading purpose</pre><pre><br>//user reducer types<br>export const SET_AUTHENTICATED=’SET_AUTHENTICATED’;<br>export const SET_UNAUTHENTICATED=’SET_UNAUTHENTICATED’;<br>export const SET_USER=’SET_USER’;<br>export const LOADING_USER=’LOADING_USER’;</pre><pre>//UI reducer types<br>export const SET_ERRORS=’SET_ERRORS’;<br>export const LOADING_UI=’LOADING_UI’;<br>export const CLEAR_ERRORS=’CLEAR_ERRORS’;</pre><p>In “actions” folder we will create userActions.ts file and in “reducers” folder we create userReducers.ts &amp; uiReducers.ts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*smWZIjapeOpYxlIo7aXC8A.png" /></figure><pre>//in useActions.ts file<br>import { SET_USER, SET_ERRORS, LOADING_UI, CLEAR_ERRORS, SET_UNAUTHENTICATED, LOADING_USER } from ‘../types’<br>import axios from ‘axios’;</pre><pre>export const loginUser = (userData: any, history: any) =&gt; (dispatch: any) =&gt; {<br> dispatch({ type: LOADING_UI })</pre><pre>axios.post(‘login’, userData)<br> .then((res) =&gt; {<br> const token = `Bearer ${res.data.token}`;<br> localStorage.setItem(‘token’, `Bearer ${res.data.token}`);//setting token to local storage<br> axios.defaults.headers.common[‘Authorization’] = token;//setting authorize token to header in axios<br> dispatch(getUserData());<br> dispatch({ type: CLEAR_ERRORS });<br> console.log(‘success’);<br> history.push(‘/’);//redirecting to index page after login success</pre><pre>})<br> .catch((err) =&gt; {<br> console.log(err);<br> dispatch({<br> type: SET_ERRORS,<br> payload: err.response.data</pre><pre>});</pre><pre>});<br>}</pre><pre>//for fetching authenticated user information<br>export const getUserData = () =&gt; (dispatch: any) =&gt; {<br> dispatch({ type: LOADING_USER });<br> axios.get(‘/user’)<br> .then(res =&gt; {<br> console.log(‘user data’, res.data);</pre><pre>dispatch({<br> type: SET_USER,<br> payload: res.data</pre><pre>});</pre><pre>}).catch(err =&gt; {<br> console.log(err);</pre><pre>});</pre><pre>}</pre><pre>export const logoutUser = () =&gt; (dispatch: any) =&gt; {<br> localStorage.removeItem(‘token’);<br> delete axios.defaults.headers.common[‘Authorization’]<br> dispatch({<br> type: SET_UNAUTHENTICATED</pre><pre>});<br> window.location.href = ‘/login’;//redirect to login page</pre><pre>};</pre><pre>NOTE:your server must return response like as follow for getting the authenticated user information getUserData function must return response as</pre><pre>{<br> “credentials”: {<br> “createdAt”: “2020–01–30T10:29:44.898Z”,<br> “email”: “<a href="/service/mailto:bikash@gmail.com">bikash@gmail.com</a>”,<br> “userId”: “D4hCBB4RcAdTjawNCQ0K4ItED563”<br> }<br>}</pre><pre>loginUser function must return token after successful login as:</pre><pre>{<br>    &quot;token&quot;: &quot;eyJhbGciOiJSUzI1NiIsImtpZCI6IjI1OTc0MmQyNjlhY2IzNWZiNjU3YzBjNGRkMmM3YjcyYWEzMTRiNTAiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vcGFya2l0LTI3YTQ4IiwiYXVkIjoicGFya2l0LTI3YTQ4IiwiYXV0aF90aW1lIjoxNTgwNjM3MzgyLCJ1c2VyX2lkIjoiRDRoQ0JCNFJjQWRUamF3TkNRMEs0SXRFRDU2MyIsInN1YiI6IkQ0aENCQjRSY0FkVGphd05DUTBLNEl0RUQ1NjMiLCJpYXQiOjE1ODA2MzczODIsImV4cCI6MTU4MDY0MDk4MiwiZW1haWwiOiJwYWRhbTEyQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJwYWRhbTEyQGdtYWlsLmNvbSJdfSwic2lnbl9pbl9wcm92aWRlciI6InBhc3N3b3JkIn19.M0hTKqNb_0_3qmqS7xiI2I3mDpm6_gaAEIzRBydiu89pzaBJPXZ1BngdLQeJ2_JOh6GJBHDDeX52yM-DZdHoK6cC93ugqMjz7bzegf5YJzdYEtBPHFKvaDUQEgzgGhGbU_jl5xL09uIixPgOChw3zWbVAbvj4ZjJrT4u5aC96txhDA9gMPtRLq-9VoL4SQTRjOc-_vP08SylWP1oklMgsCfEGFCk81zcEsGEHfHwH_dIcj208G483lzD29Ghqmo3nKGp6u3eeXLxoyop8hKQsJUbvJK9zZmobfqZfghuDgiMj5_LqImmTeQR6jw7_S1NK0uDMcQl3G0lxezvS0n53w&quot;<br>}</pre><pre>//in userReducer.ts<br>import { SET_USER, SET_AUTHENTICATED, SET_UNAUTHENTICATED, LOADING_USER } from ‘../types’<br>const initialState = {<br> authenticated: false,<br> credentials: {},<br> loading: false<br>}</pre><pre><br>export default function (state = initialState, action:any) {<br> switch (action.type) {<br> case SET_AUTHENTICATED:<br> return {<br> …state,<br> authenticated: true<br> };<br> case SET_UNAUTHENTICATED:<br> return initialState;<br> case SET_USER:<br> return {<br> authenticated: true,<br> loading:false,<br> …action.payload<br> };</pre><pre>case LOADING_USER:<br> return {<br> …state,<br> loading: true<br> };<br> default:<br> return state;</pre><pre>}</pre><pre>}</pre><pre>//in uiReducer.ts</pre><pre>import { SET_ERRORS, LOADING_UI, CLEAR_ERRORS } from ‘../types’<br>const initialState = {<br> loading: false,<br> errors: null<br>}</pre><pre>export default function (state = initialState, action:any) {</pre><pre>switch (action.type) {<br> case SET_ERRORS:<br> return {<br> …state,<br> loading: false,<br> errors: action.payload<br> };<br> case CLEAR_ERRORS:<br> return {<br> …state,<br> loading: false,<br> errors: null</pre><pre>};<br> case LOADING_UI:<br> return {<br> …state,<br> loading: true<br> }<br> default:<br> return state;</pre><pre>}<br>}</pre><pre><br>//in store.ts</pre><pre>import { createStore, combineReducers, applyMiddleware, compose } from ‘redux’<br>import thunk from ‘redux-thunk’<br>import userReducer from ‘./reducers/userReducer’<br>import uiReducer from ‘./reducers/uiReducer’<br>const initialState = {};<br>const middleware = [thunk];<br>//this is for redux devtool purpose<br>declare global {</pre><pre>interface Window {<br> __REDUX_DEVTOOLS_EXTENSION__?: typeof compose;</pre><pre>}<br>}</pre><pre>const reducer = combineReducers({<br> user: userReducer,//user key ma store gareko<br> UI: uiReducer</pre><pre>});</pre><pre>const store = createStore(reducer, initialState, compose(applyMiddleware(…middleware), (window.__REDUX_DEVTOOLS_EXTENSION__ &amp;&amp; window.__REDUX_DEVTOOLS_EXTENSION__()) as any));</pre><pre>export default store;</pre><p>Now inside components folder we will create 2 functional components Login.tsx,Index.tsx<br>NOTE:Login.tsx is our guest component that doesn;t need to be secure with authentication. We will use material UI for login page.</p><p>// with npm<br>npm install @material-ui/core</p><p>// with yarn<br>yarn add @material-ui/core<br>Index.tsx is our private component that need to be secure and only authenticated user can access it</p><pre>//in Login.tsx inside components<br>import React, { useState, useEffect } from “react”;<br>import CssBaseline from ‘<a href="http://twitter.com/material">@material</a>-ui/core/CssBaseline’;<br>import TextField from ‘<a href="http://twitter.com/material">@material</a>-ui/core/TextField’;<br>import FormControlLabel from ‘<a href="http://twitter.com/material">@material</a>-ui/core/FormControlLabel’;<br>import Checkbox from ‘<a href="http://twitter.com/material">@material</a>-ui/core/Checkbox’;<br>import Grid from ‘<a href="http://twitter.com/material">@material</a>-ui/core/Grid’;<br>import Typography from ‘<a href="http://twitter.com/material">@material</a>-ui/core/Typography’;<br>import { makeStyles } from ‘<a href="http://twitter.com/material">@material</a>-ui/core/styles’;<br>import Container from ‘<a href="http://twitter.com/material">@material</a>-ui/core/Container’;<br>import { Paper, Box } from ‘<a href="http://twitter.com/material">@material</a>-ui/core’;<br>import Button from ‘<a href="http://twitter.com/material">@material</a>-ui/core/Button’;<br>import { Link, useHistory, useLocation } from ‘react-router-dom’<br>import CircularProgress from ‘<a href="http://twitter.com/material">@material</a>-ui/core/CircularProgress’;<br>//redux stuff<br>import { connect } from ‘react-redux’;<br>import { loginUser } from ‘../../redux/actions/userActions’</pre><pre>function Login(props: any) {</pre><pre>const [values, setValues] = useState({<br> email: “”,<br> password: “”<br> } as userDataProps);<br> const [errors, setErrors] = useState({} as formError);<br> const [loading, setLoading] = useState(false);</pre><pre>useEffect(() =&gt; {<br> if (props.UI.errors) {<br> setErrors(props.UI.errors);</pre><pre>}<br> setLoading(props.UI.loading);</pre><pre>}, [props.UI])</pre><pre>const handleSubmit = (e: any) =&gt; {<br> e.preventDefault();<br> setLoading(true);</pre><pre>//your client side validation here</pre><pre>//after success validation<br> const userData = {<br> email: values.email,<br> password: values.password,</pre><pre>};<br> props.loginUser(userData, props.history);<br> }</pre><pre>const handleChange = (e: any) =&gt; {<br> e.persist();<br> setValues(values =&gt; ({<br> …values,<br> [e.target.name]: e.target.value<br> }));<br> };</pre><pre>return (<br> &lt;Box&gt;<br> &lt;Box className={classes.box}&gt;<br> &lt;Typography variant=”h4&quot;&gt;<br> &lt;Box fontWeight={600} letterSpacing={3}&gt;<br> SIGN IN<br> &lt;/Box&gt;<br> &lt;/Typography&gt;<br> &lt;/Box&gt;<br> &lt;Container<br> component=”main”<br> <br> maxWidth=”md”&gt;<br> &lt;CssBaseline /&gt;<br> &lt;Grid<br> container<br> alignContent=”center”<br> alignItems=”center”<br> justify=”center”<br> <br> spacing={3}&gt;<br> &lt;Grid<br> item<br> md={3}&gt;<br> &lt;img src={your_logo_here} alt=”My Logo” /&gt;<br> &lt;/Grid&gt;<br> &lt;Grid item md={9}&gt;<br> &lt;Paper&gt;<br> &lt;Box&gt;<br> &lt;TextField<br> variant=”outlined”<br> margin=”none”<br> value={values.email}<br> fullWidth<br> id=”email”<br> label=”Email Address”<br> name=”email”<br> type=”email”<br> onChange={handleChange}<br> helperText={errors.email}<br> error={errors.email ? true : false}<br> /&gt;<br> &lt;TextField<br> variant=”outlined”<br> margin=”normal”<br> value={values.password}<br> fullWidth<br> name=”password”<br> label=”Password”<br> type=”password”<br> onChange={handleChange}<br> helperText={errors.password}<br> error={errors.password ? true : false}<br> /&gt;<br> {errors.message &amp;&amp; (<br> &lt;Typography variant=”body2&quot;&gt;<br> {errors.message}<br> &lt;/Typography&gt;<br> )}<br> &lt;Grid container&gt;<br> &lt;Grid item sm={6} md={6}&gt;<br> &lt;FormControlLabel<br> <br> control={<br> &lt;Checkbox value=”remember” color=”primary” /&gt;<br> }<br> label=”Remember me”<br> /&gt;<br> &lt;/Grid&gt;<br> &lt;Grid item sm={6} md={6}&gt;<br> &lt;Link to=”#”&gt;<br> Forgot password?<br> &lt;/Link&gt;<br> &lt;/Grid&gt;<br> &lt;/Grid&gt;<br> &lt;Button type=”submit” variant=”contained” color=”primary” disabled={loading}&gt;<br> Login<br> {loading &amp;&amp; (&lt;CircularProgress className={classes.loader} size={30} color=”secondary” /&gt;)}<br> &lt;/Button&gt;<br> <br> &lt;/Box&gt;<br> &lt;/Paper&gt;<br> &lt;/Grid&gt;<br> &lt;/Grid&gt;<br> &lt;/Container &gt;<br> &lt;/Box&gt;<br> )<br>}</pre><pre>//this map the states to our props in this functional component<br>const mapStateToProps = (state: any) =&gt; ({<br> user: state.user,<br> UI: state.UI</pre><pre>});</pre><pre>//this map actions to our props in this functional component<br>const mapActionsToProps = {<br> loginUser<br>};<br>export default connect(mapStateToProps, mapActionsToProps)(Login)</pre><p>Now we will create 3 files inside utils as follow<br>-&gt;GuestRoute.tsx<br>-&gt;PrivateRoute.tsx<br>-&gt;CheckAuthentication.ts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*JRNEKPb0oeQWi6u6Wjysew.png" /></figure><pre>//in GuestRoute.tsx<br>import React from ‘react’<br>import { Route, Redirect,RouteProps } from ‘react-router-dom’<br>//redux stuff<br>import { connect } from ‘react-redux’</pre><pre>interface MyRouteProps extends RouteProps{<br> component:any;<br> authenticated:boolean;<br> rest?:any</pre><pre>}</pre><pre>const GuestRoute: React.SFC&lt;MyRouteProps&gt;= ({ component: Component, authenticated, …rest }) =&gt; (<br> &lt;Route<br> {…rest}<br> render={(props) =&gt;<br> authenticated ?<br> &lt;Redirect to=’/’ /&gt; :<br> &lt;Component {…props}<br> /&gt;}</pre><pre>/&gt;<br>);</pre><pre>const mapStateToProps = (state:any) =&gt; ({<br> authenticated: state.user.authenticated</pre><pre>});</pre><pre>export default connect(mapStateToProps)(GuestRoute)</pre><p>The Guest Route is for non-authenticated user.If user if already authenticated then it will redirect user to Index page</p><pre>//in PrivateRoute.tsx<br>import React from ‘react’<br>import { Route, Redirect,RouteProps } from ‘react-router-dom’</pre><pre>import { connect } from ‘react-redux’<br>interface MyRouteProps extends RouteProps{<br> component:any;<br> authenticated:boolean;<br> rest?:any</pre><pre>}</pre><pre>const PrivateRoute: React.SFC&lt;MyRouteProps&gt; = ({ component: Component, authenticated, …rest }:any) =&gt; (<br> &lt;Route<br> {…rest}<br> render={(props) =&gt;<br> authenticated ?<br> &lt;Component {…props} /&gt; :<br> &lt;Redirect to=’/login’ /&gt;</pre><pre>}</pre><pre>/&gt;<br>);</pre><pre>const mapStateToProps = (state:any) =&gt; ({<br> authenticated: state.user.authenticated</pre><pre>});</pre><pre>export default connect(mapStateToProps)(PrivateRoute)</pre><p>The PrivateRoute is only for authenticated user,if user is authenticated then only it can access to respective page otherwise it will redirect to login page</p><pre>//in CheckAuthentication.ts</pre><pre>import jwtDecode from ‘jwt-decode’;//you must install jwt-decode using npm<br>import { logoutUser, getUserData } from ‘../redux/actions/userActions’<br>import store from ‘../redux/store’;<br>import axios from ‘axios’;<br>import { SET_AUTHENTICATED } from ‘../redux/types’</pre><pre>export const CheckAuthentication = () =&gt; {<br> const authToken = localStorage.token;</pre><pre>if (authToken) {<br> const decodedToken:any = jwtDecode(authToken);<br> console.log(decodedToken.iss);</pre><pre>if (decodedToken.exp * 1000 &lt; Date.now()) {<br> store.dispatch(logoutUser());</pre><pre>} else {<br> store.dispatch({ type: SET_AUTHENTICATED });<br> axios.defaults.headers.common[‘Authorization’] = authToken;<br> store.dispatch(getUserData());<br> }</pre><pre>}</pre><pre>}</pre><p>The CheckAuthentication functions will check the authenticated user token ,if user is authenticated then it will set SET_AUTHENTICATED with authentication status true otherwise logout the user from our app</p><pre>//Finally in App.tsx<br>import React, { useEffect } from ‘react’;<br>import ‘./App.css’;<br>import { BrowserRouter as Router, Switch, Route } from ‘react-router-dom’<br>import Login from ‘./components/Login.tsx’<br>import Index from ‘./components/Index.tsx’<br>import GuestRoute from ‘./utils/GuestRoute’<br>import PrivateRoute from ‘./utils/PrivateRoute’</pre><pre>//redux stuff<br>import { Provider } from ‘react-redux’;<br>import store from ‘./redux/store’;<br>import { CheckAuthentication } from ‘./utils/CheckAuthentication’</pre><pre>const App: React.FC = () =&gt; {<br> useEffect(() =&gt; {<br> CheckAuthentication();</pre><pre>}, []);</pre><pre>return (<br> &lt;div className=”App”&gt;<br> &lt;Provider store={store}&gt;<br> &lt;Router&gt;<br> &lt;Switch&gt;<br> &lt;PrivateRoute<br> exact<br> path=”/”<br> component={Index} /&gt;</pre><pre>&lt;GuestRoute<br> exact<br> path=’/login’<br> component={Login} /&gt;</pre><pre>&lt;/Switch&gt;<br> &lt;/Router&gt;<br> &lt;/Provider&gt;<br> &lt;/div&gt;<br> )<br>}</pre><pre>export default App;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e2dd5616e30" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/how-to-setup-authentication-in-react-typescript-and-redux-6e2dd5616e30">How to setup authentication in react typescript and redux</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to setup authentication using node server and firebase cloud functions]]></title>
            <link>https://articles.wesionary.team/how-to-setup-authentication-using-node-server-and-firebase-cloud-functions-a1fb176a134f?source=rss-deed02778f10------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1fb176a134f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firebaseauthentication]]></category>
            <dc:creator><![CDATA[bikash bhandari]]></dc:creator>
            <pubDate>Thu, 30 Jan 2020 10:34:00 GMT</pubDate>
            <atom:updated>2020-01-30T11:52:55.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6XrfPdv-MhN3AswvVsKkjA.jpeg" /></figure><p>From this tutorial, we can create a “Backend” in node server using firestore cloud functions for signIn and signUp users.</p><p>What is Node.js?<br>1.Node.js is an open source server environment that uses javascript on the server<br>2.It is a platform built on Chrome’s JavaScript library for building fast and scalable network applications.</p><p>Why Node JS?<br>1.Node.js is rich library which include various JavaScript modules which simplifies the development of web applications to a great extent.<br>2.Asynchronous and Event Driven:The APIs of Node.js are asynchronous, that means, non-blocking.It means a Node.js based server never waits for an API to return data.<br>3.Very Fast − Since Node.js is built on Google Chrome’s V8 JavaScript Engine, it’s library is very fast in code execution.<br>4.No Buffering − The applications build using Node.js never buffer any data. These applications simply output the data in chunks.</p><p>What is Cloud Firestore?<br>1.A Cloud Firestore is a flexible, noSQl database for mobile, web, and server development from Firebase and Google Cloud Platform.<br>2.The Cloud Functions runs JavaScript code in the server when deployed and this allows you to write code like as API Keys and Secrets, payment processes etc and alose manage Cloud Storage and Database as admin.</p><h3><strong>Environment setup</strong></h3><p>At First ,all you need have installed Node.js, at least the version 6.9.x or higher. You can download and install for your SO from the Node.js project website <a href="https://nodejs.org/en/download/">https://nodejs.org/en/download/</a>. When you installed it, you can install the Firebase CLI in order to init a new project and setup functions feature. You can install it globally using npm:</p><pre>$ npm install -g firebase-tools</pre><p>Now check your firebase version like this:</p><pre>$ firebase version<br>&gt; 3.9.1</pre><p><strong>NOTE:</strong><em>Make sure you have the Firebase CLI version 3.5.x or higher, if not the functions feature may not work.</em></p><p>Now create a project folder and locate inside it using terminal and then login to the firebase by typing:</p><pre>$firebase login</pre><p>NOTE:if you are already loggedin and want to change your another email to login then type:$ firebase logout and again login, You must be logged in to your account with same email which also belongs to your firebase account <br>NoTE:You must create app in firebase <a href="https://youtu.be/6juww5Lmvgo">https://youtu.be/6juww5Lmvgo</a></p><p>Now Locate to your project folder you created earlier and then type:</p><pre>$ firebase init</pre><p>This will create a new project in Firebase Console Dashboard.<br>You will see screen as below and hit spacebar on functions to select and choose “Functions:configure and depoly cloud functions”</p><pre>&gt; Which Firebase CLI features do you want to setup for this folder? Press Space to select features, then Enter to confirm your choices. (Press &lt;space<br>&gt; to select)<br>❯◯ Database: Deploy Firebase Realtime Database Rules<br> ◯ Functions: Configure and deploy Cloud Functions<br> ◯ Hosting: Configure and deploy Firebase Hosting sites</pre><ul><li>&gt;Choose use existing project if you have already created or create new one <br>-&gt;Choose language javascript<br>-&gt; EsLint No(Your choice).<br>-&gt;install dependencies or type npm install<br>Then finally deploy the function to firebase using :</li></ul><pre>$ firebase deploy<br>You will get api access URL for every functions like https://us-central1-parkit-27a48.cloudfunctions.net<a href="https://us-central1-social-app-1e6ec.cloudfunctions.net/helloWorld">/helloWorld</a></pre><p>Now you will see the functions folder, locate inside functions folder where you can see index.js which is main file..this functions folder is node server. We will create out folder structure as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*4rpORFv4gbWfLQmnV5pTpg.png" /></figure><p>Now we will use express for api route so install it inside functions folder</p><pre>$ npm install — save express</pre><pre><br>Inside your functions folder create 2 new folders as shown in above image</pre><pre>-&gt;handlers</pre><pre>-&gt;utils <br>Inside handlers folder create auth.js where we will write logic for signin and signup user</pre><pre>Similarly,inside utils folder create 3 files admin.js(for firebase admin),config.js(for firebase api setting),helpers.js (for creating custom helper functions)</pre><pre><strong>#inside utils/config.js</strong><br>module.exports = {<br> apiKey: “your firebase apikey”,<br> authDomain: “your app domain”,<br> databaseURL: “your databse url”,<br> projectId: “your project id”,<br> storageBucket: “your storage bucket”,<br> messagingSenderId: “your messenger id”,<br> appId: “your app id”,<br> <br> };</pre><pre><strong>#inside utils/admin.js</strong><br>const admin = require(“firebase-admin”);<br>admin.initializeApp();<br>const db = admin.firestore();</pre><pre>const firebase = require(‘firebase’);</pre><pre>module.exports = { admin, db,firebase};</pre><pre><strong>#inside utils/helper.js</strong></pre><pre>//for checking empty string or not<br>const isEmpty = (string) =&gt; {<br> if (string.trim() === ‘’) {<br> return true;<br> } else {<br> return false;<br> }</pre><pre>}<br>//for checking valid email address with regualr expression<br>const isEmail = (email) =&gt; {<br> const regx = /^(([^&lt;&gt;()\[\]\\.,;:\s@”]+(\.[^&lt;&gt;()\[\]\\.,;:\s@”]+)*)|(“.+”))@((\[[0–9]{1,3}\.[0–9]{1,3}\.[0–9]{1,3}\.[0–9]{1,3}\])|(([a-zA-Z\-0–9]+\.)+[a-zA-Z]{2,}))$/;<br> if (email.match(regx)) {<br> return true<br> } else {<br> return false<br> }<br>}</pre><pre>//for validating signup data<br>exports.validateSignUPData = (data) =&gt; {</pre><pre>let errors = {};</pre><pre>if (isEmpty(data.email)) {<br> errors.email = “Email Filed Is Required!”</pre><pre>} else if (!isEmail(data.email)) {<br> errors.email = “Must be valid email address”;</pre><pre>}</pre><pre>if (data.password !== data.confirmPassword) {<br> errors.confirmPassword = “Password Did not match”;<br> }</pre><pre>return {<br> errors,<br> valid: Object.keys(errors).length === 0 ? true : false<br> }<br>}</pre><pre>//for validating signin data<br>exports.validateLoginData = (data) =&gt; {<br> let errors = {}</pre><pre>if (isEmpty(data.email)) {<br> errors.email = “Email filed is required!”<br> } else if (isEmpty(data.password)) {<br> errors.password = “Password filed is required!”</pre><pre>} else if (!isEmail(data.email)) {<br> errors.email = “Must be valid email address”</pre><pre>}</pre><pre>return {<br> errors,<br> valid: Object.keys(errors).length === 0 ? true : false<br> }<br>}</pre><pre><strong>#inside handlers/auth.js</strong><br>const { admin, db, firebase } = require(‘../utils/admin’);<br>const { validateSignUPData, validateLoginData } = require(‘../utils/helper’)</pre><pre>//<br>exports.signUp = (req, res) =&gt; {<br> const newUser = {<br> email: req.body.email,<br> password: req.body.password,<br> confirmPassword: req.body.confirmPassword,</pre><pre>};</pre><pre>const { valid, errors } = validateSignUPData(newUser);<br> if (!valid)//checking validation<br> return res.status(400).json(errors);<br> let token, userId;<br> db.collection(‘users’).where(‘email’, ‘==’, newUser.email).get()<br> .then(doc =&gt; {<br> if (doc.exists) {<br> return res.status(400).json({ handle: ‘The user id already taken’ });<br> } else {<br> return firebase.auth().createUserWithEmailAndPassword(newUser.email, newUser.password)<br> }<br> }).then(data =&gt; {<br> userId = data.user.uid<br> return data.user.getIdToken();<br> }).then(idToken =&gt; {<br> token = idToken<br> const userCredentials = {<br> userId,<br> email: newUser.email,<br> createdAt: new Date().toISOString(),</pre><pre>}</pre><pre>db.doc(`/users/${userId}`).set(userCredentials);</pre><pre>}).then(() =&gt; {<br> return res.status(201).json({ token })</pre><pre>})<br> .catch(err =&gt; {<br> if (err.code == ‘auth/email-already-in-use’) {<br> return res.status(400).json({ email: ‘Email already exist!’ })<br> }<br> return res.status(500).json({ error: err.message })<br> });</pre><pre>}</pre><pre>exports.signIn = (req, res) =&gt; {<br> const user = {<br> email: req.body.email,<br> password: req.body.password<br> }</pre><pre>const { valid, errors } = validateLoginData(user);</pre><pre>if (!valid) return res.status(400).json(errors)<br> firebase.auth().signInWithEmailAndPassword(user.email, user.password)//firebase signin method<br> .then(data =&gt; {<br> console.log(JSON.stringify(data))<br> return data.user.getIdToken();<br> }).then(token =&gt; {<br> return res.json({ token })<br> }).catch(err =&gt; {<br> if (err.code == ‘auth/wrong-password’ || err.code == ‘auth/user-not-found’) {<br> return res.status(403).json({ message: ‘Wrong credentials, Please try again’ });<br> }<br> return res.status(500).json({ error: err.code })<br> })</pre><pre>}</pre><pre><strong>#Finally in functions/index.js<br></strong>const { admin, db } = require(‘./utils/admin’)<br>const functions = require(‘firebase-functions’);<br>const app = require(‘express’)();//initializaing the app<br>const firebaseConfig = require(‘./utils/config’)<br>const firebase = require(‘firebase’);<br>firebase.initializeApp(firebaseConfig);// Initializing Firebase<br>const { signIn,signUp,resetPassword } = require(‘./handlers/auth’);</pre><pre><strong>Creating Authentication routes:</strong><br>app.post(‘/register’,signUp);<br>app.post(‘/login’,signIn);<br></pre><pre>exports.api=functions.https.onRequest(app);//this will add api prefix to our url and gives api url like https://us-central1-parkit-27a48.cloudfunctions.net/api/</pre><p>Now ,we can signup and login using postman for test</p><h3><strong>For User SignUp</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWKbQmHcvo4NeclRRRKRTQ.png" /></figure><h3>For User SignIn</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fqcgj0HKVV3XDylj5kH2dQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1fb176a134f" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/how-to-setup-authentication-using-node-server-and-firebase-cloud-functions-a1fb176a134f">How to setup authentication using node server and firebase cloud functions</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>