<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: SangeetaGogoi</title>
    <description>The latest articles on DEV Community by SangeetaGogoi (@sangeetagogoi).</description>
    <link>https://dev.to/sangeetagogoi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F721201%2Fd7eb540f-cd36-4f31-8945-1dbb3b63ff29.jpg</url>
      <title>DEV Community: SangeetaGogoi</title>
      <link>https://dev.to/sangeetagogoi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sangeetagogoi"/>
    <language>en</language>
    <item>
      <title>Most commonly used React Hooks</title>
      <dc:creator>SangeetaGogoi</dc:creator>
      <pubDate>Sat, 16 Oct 2021 13:24:57 +0000</pubDate>
      <link>https://dev.to/sangeetagogoi/most-commonly-used-react-hooks-1b9l</link>
      <guid>https://dev.to/sangeetagogoi/most-commonly-used-react-hooks-1b9l</guid>
      <description>&lt;p&gt;We are going to learn about React hooks in this blog.&lt;br&gt;
Let us start with its introduction:&lt;/p&gt;

&lt;p&gt;Hooks are new addition to React that lets us use state, and other React features such as Lifecycle methods, without writing a class.&lt;/p&gt;

&lt;p&gt;Types of Hooks in React are:&lt;/p&gt;

&lt;p&gt;&lt;b&gt; 1.State Hook &lt;/b&gt;&lt;br&gt;
Using the useState hook lets us add a React state to our functional component.The useState function is a built-in hook that can be imported from the react package.&lt;/p&gt;
&lt;h4&gt;
  
  
  Importing useState hook from react
&lt;/h4&gt;

&lt;p&gt;&amp;amp; Declaring a State Variable:&lt;/p&gt;

&lt;p&gt;In a functional component we directly call the useState hook inside our component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {useState} from "react";

function Example(){
const [time, setTime] = useState(0);
//..
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;useState hook returns a pair of values: the current state and a function that updates it. This is why we write const [time, setTime] = useState().&lt;/p&gt;

&lt;h4&gt;
  
  
  Reading a State
&lt;/h4&gt;

&lt;p&gt;In a functional component we can use 'time' as :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  &amp;lt;p&amp;gt;You clicked {time} times&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Updating a state
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button onClick={() =&amp;gt; setTime(time + 1)}&amp;gt;
    Submit
&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Putting together the whole code:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {useState} from "react";

function Example(){
const [time, setTime] = useState(0);

 &amp;lt;p&amp;gt;You clicked {time} times&amp;lt;/p&amp;gt;
&amp;lt;button onClick={() =&amp;gt; setTime(time + 1)}&amp;gt;
    Submit
  &amp;lt;/button&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;b&gt; 2. Effect hook&lt;/b&gt; &lt;/p&gt;

&lt;p&gt;The purpose of the useEffect hook is to allow us to perform side effects within a functional components. Examples of side effects we will typically perform in a React application are: data fetching, setting up a subscription, and manually changing the DOM in React components.&lt;/p&gt;

&lt;p&gt;It accepts two arguments:&lt;/p&gt;

&lt;p&gt;1.callback function &lt;br&gt;
 2.Dependencies Array&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(callback[, dependencies]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can put side-effect logic into the callback function, then use the dependencies argument to control when we want the side-effect to run. That’s the purpose of useEffect().&lt;/p&gt;

&lt;p&gt;&lt;b&gt; The dependencies of useEffect() &lt;/b&gt; &lt;/p&gt;

&lt;p&gt;Three cases with dependencies array:&lt;br&gt;
&lt;b&gt; 1. No dependency array &lt;/b&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect } from 'react';

function App(){
useEffect(() =&amp;gt; {

    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the callback gets fired after the initial rendering and everytime any of the component state changes.&lt;/p&gt;

&lt;p&gt;&lt;b&gt; 2. Empty dependency array &lt;/b&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect } from 'react';

function App(){
 useEffect(() =&amp;gt; {

    }, []);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the callback gets fired only once after the initial rendering.&lt;/p&gt;

&lt;p&gt;&lt;b&gt; 3. With dependencies &lt;/b&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect } from 'react';

function App(){
useEffect(() =&amp;gt; {

    }, [dependency1, dependency2]);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the callback gets fired after the initial rendering and every time any of the dependencies in the dependencies array changes.&lt;/p&gt;

&lt;p&gt;&lt;b&gt; Summary &lt;/b&gt;:&lt;/p&gt;

&lt;p&gt;useEffect(callback, dependencies) invokes the callback after initial mounting, and on later renderings, if any value inside dependencies has changed.&lt;/p&gt;




&lt;p&gt;&lt;b&gt; 3. Ref hook &lt;/b&gt;&lt;/p&gt;

&lt;p&gt;useRef() is JavaScript function, which creates and returns a mutable JavaScript object.&lt;br&gt;
This hook accepts some value and returns an object with the given value. &lt;/p&gt;

&lt;p&gt;&lt;b&gt; Syntax &lt;/b&gt;&lt;br&gt;
Importing the ref hook and setting up looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {useRef} from 'react';

const refContainer = useRef(initialValue);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Use cases
&lt;/h4&gt;

&lt;p&gt;1.Getting access to DOM nodes&lt;br&gt;
The use case of useRef() is getting access to DOM nodes. If we want to pass the value we get from useRef() as a ref prop on any React element, React will set the .current property of an element to the corresponding DOM node. This allows us to do things like grab input values or set focus, for example in the Form below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {useRef} from 'react';

const Form =() =&amp;gt;{

const nameRef = useRef();

//Here variable Name contains the current value of input field 
const name = nameRef.current.value; 

return(
    &amp;lt;&amp;gt;
      &amp;lt;label&amp;gt;
        Name:
        &amp;lt;input
          placeholder="name"
          type="text"
          ref={nameRef}  
        /&amp;gt;
      &amp;lt;/label&amp;gt;
      //Here we added an event which will set the input to focus when user clicks on the button
      &amp;lt;button onClick={() =&amp;gt; nameRef.current.focus()}&amp;gt;
        Focus Name Input
      &amp;lt;/button&amp;gt;
  &amp;lt;/&amp;gt;
)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2.Storing Values
&lt;/h4&gt;

&lt;p&gt;A unique way to implement a useRef() hook is to use it to store values instead of DOM references. These values can either be a state that does not need to change too often or a state that should not trigger full re-rendering of the component. This can be used when we want to implement toggle function, for example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let toggled = useRef(false);

  const handleToggle  = () =&amp;gt; {
    toggled.current = !toggled.current;
  }

return(
&amp;lt;&amp;gt;
   &amp;lt;label onMouseMove={handleToggle}&amp;gt;&amp;lt;/label&amp;gt;
&amp;lt;/&amp;gt;
)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;b&gt; 4.Context hook &lt;/b&gt;&lt;/p&gt;

&lt;p&gt;useContext hook is used to create common data that can be accessed throughout the component hierarchy without passing the props down manually to each level. Context defined will be available to all the child components without involving props.&lt;/p&gt;

&lt;h4&gt;
  
  
  Importing the hook from the React library:
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {useContext} from 'react';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We call useContext() function, which accepts context object as argument and returns current context value:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const contextValue = useContext(MyContext);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The context object should be created above the useContext() hook before the hook is called (or imported from another file).&lt;/p&gt;

&lt;p&gt;Usage of useContext() in functional component is same as we would use Context API, except that the hook works with a MyContext.Provider and MyContext.Consumer component in one call.&lt;/p&gt;

&lt;p&gt;Let us consider, we are building app where we have a button and by clicking on it the status of authentication is changed from Yes to No.&lt;/p&gt;

&lt;p&gt;Firstly we need to create Context:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Creating the context object and passing the default values. 

export const authContext = React.createContext({status:null,login:()=&amp;gt;{}}); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we import Context to our file and use it's values anywhere we find it necessary:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {AuthContext} from './authContext';
import {useContext} from 'react';

export const Auth = () =&amp;gt;{

const auth = useContext(AuthContext); 

return ( 
    &amp;lt;&amp;gt; 
      &amp;lt;h1&amp;gt;Are you authenticated?&amp;lt;/h1&amp;gt; 
      {auth.status ?  &amp;lt;p&amp;gt;Yes you are&amp;lt;/p&amp;gt; :  &amp;lt;p&amp;gt;No you are not&amp;lt;/p&amp;gt; 
       } 
      &amp;lt;button onClick={auth.login}&amp;gt;Click To Login&amp;lt;/button&amp;gt; 
    &amp;lt;/&amp;gt; 
  ); 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;b&gt; Summary &lt;/b&gt;&lt;/p&gt;

&lt;p&gt;React’s useContext hook makes it easy to pass data throughout your app without manually passing props down the tree.&lt;/p&gt;


  

&lt;p&gt;&lt;b&gt; References For this blog &lt;/b&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://reactjs.org/"&gt;https://reactjs.org/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dev.to/olenadrugalya/basic-hooks-in-react-usecontext-4bie"&gt;https://dev.to/olenadrugalya/basic-hooks-in-react-usecontext-4bie&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>Lesser used React Hooks</title>
      <dc:creator>SangeetaGogoi</dc:creator>
      <pubDate>Sat, 16 Oct 2021 13:18:17 +0000</pubDate>
      <link>https://dev.to/sangeetagogoi/lesser-used-react-hooks-1fnf</link>
      <guid>https://dev.to/sangeetagogoi/lesser-used-react-hooks-1fnf</guid>
      <description>&lt;p&gt;In this blog we are going to talk about React hooks that are not used commonly.&lt;/p&gt;

&lt;p&gt;&lt;b&gt; 1. useMemo Hook &lt;/b&gt;  :&lt;/p&gt;

&lt;p&gt;The useMemo is a hook used in the functional component of react that returns a memoized value.In react also, we use this concept, whenever in the React component, the state and props do not change the component and the component does not re-render, it shows the same output.&lt;/p&gt;

&lt;p&gt;&lt;b&gt; Syntax &lt;/b&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const memoizedValue = useMemo(() =&amp;gt; computeExpensiveValue(a, b), [a, b]);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;useMemo takes in a function and an array of dependencies. &lt;/p&gt;

&lt;p&gt;&lt;b&gt; Usage of useMemo &lt;/b&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const memoizedList = useMemo(() =&amp;gt; {
  return userList.map(user =&amp;gt; {
    return {
      ...user,
      name: someExpensiveOperation(user.name)
    } 
  }) 
}, [userList])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;b&gt; 2. useCallback Hook &lt;/b&gt; :&lt;/p&gt;

&lt;p&gt;The useCallback hook is used when we have a component in which the child is rerendering again and again without need.&lt;/p&gt;

&lt;p&gt;&lt;b&gt; Syntax &lt;/b&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const memoizedCallback = useCallback(
  () =&amp;gt; {
    doSomething(a, b);
  },
  [a, b],
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. &lt;/p&gt;

&lt;p&gt;&lt;b&gt; Purpose of useCallback &lt;/b&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function MyComponent() {
  // handleClick is re-created on each render
  const handleClick = () =&amp;gt; {
    console.log('Clicked!');
  };

  // ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;handleClick is a different function object on every rendering of MyComponent.&lt;/p&gt;

&lt;p&gt;But in some cases you need to maintain a single function instance between renderings:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;A functional component wrapped inside React.memo() accepts a function object prop&lt;/li&gt;
&lt;li&gt;When the function object is a dependency to other hooks, e.g. useEffect(..., [callback])&lt;/li&gt;
&lt;li&gt;When the function has some internal state, e.g. when the function is debounced or throttled.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That’s when useCallback(callbackFun, deps) is helpful: given the same dependency values deps, the hook returns (aka memoizes) the function instance between renderings:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useCallback } from 'react';

function MyComponent() {
  // handleClick is the same function object
  const handleClick = useCallback(() =&amp;gt; {
    console.log('Clicked!');
  }, []);

  // ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;b&gt; 3.useReducer Hook &lt;/b&gt;:&lt;/p&gt;

&lt;p&gt;useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.&lt;/p&gt;

&lt;p&gt;&lt;b&gt; Syntax &lt;/b&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [state, dispatch] = useReducer(reducer, initialArg, init);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It accepts a reducer of type (state, action) =&amp;gt; newState, and returns the current state paired with a dispatch method. (If you’re familiar with Redux, you already know how this works.&lt;/p&gt;

&lt;p&gt;Here is the countReducer example;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const initialState = { count: 0 }

const counterReducer = (state, action) =&amp;gt; {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;b&gt; Specifying the initial State &lt;/b&gt;&lt;/p&gt;

&lt;p&gt;Two ways to initialized the useReducer state;&lt;/p&gt;

&lt;p&gt;&lt;b&gt;1. Basic &lt;/b&gt; :&lt;/p&gt;

&lt;p&gt;We can just give it as a second argument to useReducer call;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [state, dispatch] = useReducer(
  countReducer,
  { count: 0 } // second argument
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;b&gt; 2. Lazy Initialization &lt;/b&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const initState = (defaultCount) =&amp;gt; ({ count: defaultCount })

const Counter = ({ counter }) =&amp;gt; {
    const [state, dispatch] = useReducer(
      countReducer,
      counter, // second argument
        initState // third argument
    );

    // Rest of the component...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;b&gt; Usage &lt;/b&gt;&lt;br&gt;
After we initialize it we just need to call dispatch functions that we are getting from useReducer hook and use it as a handler inside our elements.&lt;/p&gt;

&lt;p&gt;React guarantees that dispatch function identity is stable and won’t change on re-renders.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Counter = ({ counter }) =&amp;gt; {
    const [state, dispatch] = useReducer(countReducer, 0);

    return (
    &amp;lt;&amp;gt;
      Count: {state.count}
      &amp;lt;button onClick={() =&amp;gt; dispatch({type: 'decrement'})}&amp;gt;-&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch({type: 'increment'})}&amp;gt;+&amp;lt;/button&amp;gt;
    &amp;lt;/&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;b&gt;References &lt;/b&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://reactjs.org/docs/hooks-reference.html"&gt;https://reactjs.org/docs/hooks-reference.html&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://dmitripavlutin.com/dont-overuse-react-usecallback/"&gt;https://dmitripavlutin.com/dont-overuse-react-usecallback/&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>REST API in Express (ES6)</title>
      <dc:creator>SangeetaGogoi</dc:creator>
      <pubDate>Sat, 16 Oct 2021 13:17:08 +0000</pubDate>
      <link>https://dev.to/sangeetagogoi/rest-api-in-express-es6-23m5</link>
      <guid>https://dev.to/sangeetagogoi/rest-api-in-express-es6-23m5</guid>
      <description>&lt;p&gt;What is a REST API&lt;/p&gt;

&lt;p&gt;From &lt;a href="https://www.redhat.com/en/topics/api/what-is-a-rest-api"&gt;Redhat&lt;/a&gt; &lt;br&gt;
A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer and was created by computer scientist Roy Fielding.&lt;/p&gt;

&lt;p&gt;To create a Nodejs project (for a runtime environment) we will create a folder called rest-api and run the command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init - y

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once that is done, we will install few packages&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i --save express cors mongoose
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Discussing the packages&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Express: It is used to write the main code for the REST API&lt;/li&gt;
&lt;li&gt;Cors: Used to make requests from a different domain. Eg: Request from frontend which is hosted in &lt;a href="http://localhost:3000"&gt;http://localhost:3000&lt;/a&gt; to the backend which is &lt;a href="http://localhost:5000"&gt;http://localhost:5000&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Mongoose: Mongoose is an ORM package which we will need to communicate with MongoDB.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To run ES6 &lt;code&gt;import&lt;/code&gt; code instead of &lt;code&gt;require&lt;/code&gt; we will add this piece of code to our package.json&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"type": "module"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Paste the following code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';

import authRoutes from './auth.routes.js';

const app = express();
const port = process.env.PORT || 8000

app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(cors())

authRoutes(app);

mongoose.connect(process.env.mongoURI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() =&amp;gt; {
    console.log("Connected to Database");
}).catch(err =&amp;gt; {
    console.log('Could not connect to the database', err);
    process.exit();
});

app.listen(port, () =&amp;gt; {
    console.log('Backend is running on port: ' + port)
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Explaining the code step by step
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First we are going to import the libraries that we have installed&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import authRoutes from './auth.routes.js';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are importing a file, which we will create soon.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const app = express();
const port = process.env.PORT || 8000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the first line we are creating an instance of express to use through out the app&lt;br&gt;
In the second line we are declaring a port variable to that takes value from an &lt;code&gt;.env&lt;/code&gt; file or the value is 8000&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(cors())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;app.use(express.urlencoded({extended: true })) is a method inbuilt in express to recognize the incoming Request Object as strings or arrays. &lt;/p&gt;

&lt;p&gt;app.use(express.json()) is a method inbuilt in express to recognize the incoming Request Object as a JSON Object&lt;/p&gt;

&lt;p&gt;app.use(cors()) is using cors as a middleware for incoming requests from a different origin.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;authRoutes(app);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;authRoutes(app) here we calling authRoutes function passing the app instance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mongoose.connect(process.env.mongoURI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() =&amp;gt; {
    console.log("Connected to Database");
}).catch(err =&amp;gt; {
    console.log('Could not connect to the database', err);
    process.exit();
});

app.listen(port, () =&amp;gt; {
    console.log('Backend is running on port: ' + port)
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These lines of code are used to connect to the mongodb and also check if it's running on which port.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { register, login } from './auth.controller.js';

const authRoutes = (app) =&amp;gt; {
  app.route('/register')
    .post(register)
  app.route('/signin')
    .post(login)
}

export default authRoutes
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are routing the requests based on the method that is incoming.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import bcrypt from 'bcryptjs';
import User from './User.model.js';

export const register = (req, res) =&amp;gt; {
  const { email, password, name, dob, gender } = req.body.userDetails
  const userData = {
    email, password, name, dob, gender
  }
  if (!email || !password || !name) {
    return res.status(422).json({ error: "Please add all the credentials" })
  }
  User.findOne({ email })
    .then((data) =&amp;gt; {
      if (data) {
        res.send({ error: 'Email already registered' });
      } else {
        bcrypt.hash(password, 10, (err, hash) =&amp;gt; {
          userData.password = hash;
          User.create(userData, (err, data) =&amp;gt; {
            res.status(200).json({ msg: 'Successfully registered' });
          })
        })
      }
    })
    .catch((err) =&amp;gt; res.send({ error: err }))
};

export const login = (req, res) =&amp;gt; {

  const { email, password } = req.body.userDetails;
  User.findOne({ email: email })
    .then((user) =&amp;gt; {
      if (!user) {
        res.send({ error: 'Account not found' })
      } else {
        if (!bcrypt.compareSync(password, user.password)) {
          res.send({ error: "You entered a wrong password" })
        } else if (bcrypt.compareSync(password, user.password)) {
          delete user.password;
          res.status(200).json({ user: user.toJSON() });

        }
      }
    })
    .catch((err) =&amp;gt; res.json({ error: err }))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I will not go into the details too much but here we have written two function for login and register.&lt;/p&gt;

&lt;p&gt;While registering we are doing basic check if email, password and name are present or not. Before registering to our app, we will check if he is already present or not in the database. If he isn't present we will register him and use bcrypt to encrypt his password and save to database.&lt;/p&gt;

&lt;p&gt;While logging in we are checking if the user is present or not. If not, we send an 'Account not found' error. If present, we pull out his data from database, remove his password and send back the data to the frontend.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import mongoose from 'mongoose';

const Schema = mongoose.Schema;

const UserSchema = Schema({
  name: {
    type: String,
    maxlength: 50,
  },
  email: {
    type: String,
    trim: true,
    unique: true,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  gender: {
    type: String
  },
  dob: {
    type: Date
  }
})

const User = mongoose.model('User', UserSchema)
export default User;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lastly, this is the User schema for all the users.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
