<?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"><channel><title><![CDATA[Pratik Sah]]></title><description><![CDATA[My personal blog where I write about contents related to Node JS, Express JS, React JS, MySQL, etc.]]></description><link>https://blog.pratik.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1740073344213/6a789833-9bc9-4731-9000-27bba1871121.png</url><title>Pratik Sah</title><link>https://blog.pratik.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Mon, 08 Jun 2026 17:09:31 GMT</lastBuildDate><atom:link href="https://blog.pratik.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[React Context API for handling global state]]></title><description><![CDATA[In React, managing the global state efficiently is crucial for building complex applications.
While Redux has long been the go-to solution for centralized state management, React's Context API now provides a built-in mechanism for handling global sta...]]></description><link>https://blog.pratik.dev/react-context-api-for-handling-global-state</link><guid isPermaLink="true">https://blog.pratik.dev/react-context-api-for-handling-global-state</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Sat, 24 Jun 2023 22:27:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1608822613336/u6pXLrM8I.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In React, managing the global state efficiently is crucial for building complex applications.</p>
<p>While <strong>Redux</strong> has long been the go-to solution for centralized state management, React's Context API now provides a built-in mechanism for handling global states without the need for external libraries.</p>
<p>This article will explore how to leverage the power of the <strong>React Context API</strong> to manage global states effectively while following best practices and coding standards.</p>
<h2 id="heading-understanding-the-react-context-api">Understanding the React Context API:</h2>
<p>The React Context API allows data to be passed down the component tree without the need for prop drilling, enabling components at any level to access and update the global state.</p>
<p>By utilizing the Context API, we can simplify the process of managing the state and eliminate the need to pass props through intermediate components.</p>
<h3 id="heading-creating-a-global-state-context">Creating a Global State Context:</h3>
<p>To start using the Context API, we first need to create a context that will hold our global state.</p>
<p>We can do this by using the <code>createContext</code> function provided by React. Here's an example of how to create a global state context:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { createContext, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> GlobalStateContext = createContext();

<span class="hljs-keyword">const</span> GlobalStateProvider = <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> [globalState, setGlobalState] = useState(initialState);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">GlobalStateContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">globalState</span>, <span class="hljs-attr">setGlobalState</span> }}&gt;</span>
      {children}
    <span class="hljs-tag">&lt;/<span class="hljs-name">GlobalStateContext.Provider</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> { GlobalStateContext, GlobalStateProvider };
</code></pre>
<p>In the above code snippet, we create a context called <code>GlobalStateContext</code> using <code>createContext()</code>. We also define a provider component called <code>GlobalStateProvider</code> that wraps up our entire application. It uses the <code>useState</code> hook to initialize and manage the global state. The <code>value</code> prop of the provider exposes the state and a corresponding setter function to its child components.</p>
<h3 id="heading-accessing-global-state">Accessing Global State:</h3>
<p>Once the global state context is set up, we can access the state from any component within its descendant tree. To do this, we need to use the <code>useContext</code> hook provided by React. Here's an example of accessing the global state:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { GlobalStateContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'./GlobalStateProvider'</span>;

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { globalState, setGlobalState } = useContext(GlobalStateContext);

  <span class="hljs-comment">// Access global state variables and update state as needed</span>
  <span class="hljs-comment">// ...</span>

  <span class="hljs-keyword">return</span> (
    <span class="hljs-comment">// JSX for the component</span>
  );
};
</code></pre>
<p>In the above code, we import the <code>GlobalStateContext</code> from our previously created context file. By using the <code>useContext</code> hook, we can access the global state object and the setter function, allowing us to read and update the state within the component.</p>
<h3 id="heading-updating-global-state">Updating Global State:</h3>
<p>To update the global state, we can simply call the setter function provided by the context. This will trigger a re-render of any component that consumes the state. Here's an example of how to update the global state:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { GlobalStateContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'./GlobalStateProvider'</span>;

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { globalState, setGlobalState } = useContext(GlobalStateContext);

  <span class="hljs-keyword">const</span> updateState = <span class="hljs-function">() =&gt;</span> {
    setGlobalState({ ...globalState, <span class="hljs-attr">newValue</span>: <span class="hljs-string">'updated value'</span> });
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{updateState}</span>&gt;</span>Update Global State<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  );
};
</code></pre>
<p>In the above code, we define an <code>updateState</code> function that calls the <code>setGlobalState</code> function with a new state object. By spreading the existing global state and updating specific values, we ensure that the previous state is not lost. This approach helps maintain immutability and avoids unexpected side effects.</p>
<h3 id="heading-best-practices">Best Practices:</h3>
<p>When working with the React Context API for global state management, it's important to follow some best practices:</p>
<ol>
<li><p>Avoid excessively large global states: Keep the global state focused and only include necessary data to prevent unnecessary re-renders.</p>
</li>
<li><p>Use separate context providers for related state: If your application has multiple distinct sections with their own state, consider creating separate context providers for each.</p>
</li>
<li><p>Optimize renders with memoization: Utilize the React.memo or useMemo hooks to prevent unnecessary re-renders of components consuming the global state.</p>
</li>
<li><p>Consider using reducer pattern: For more complex state management scenarios, you can combine the Context API with the use of reducers to handle actions and state updates in a more structured manner.</p>
</li>
</ol>
<h3 id="heading-conclusion">Conclusion:</h3>
<p>The React Context API, along with the useState and useContext hooks, provides a powerful solution for managing global state in React applications. By adopting best practices and adhering to coding standards, we can effectively leverage the Context API to simplify state management and improve the scalability and maintainability of our applications.</p>
]]></content:encoded></item><item><title><![CDATA[Streamlining React Component Development with a Custom CLI]]></title><description><![CDATA[React has become one of the most popular JavaScript libraries for building user interfaces.
As a React developer, I often found myself spending valuable time manually creating components and managing CSS modules.
The lack of consistency and repetitiv...]]></description><link>https://blog.pratik.dev/streamlining-react-component-development-with-a-custom-cli</link><guid isPermaLink="true">https://blog.pratik.dev/streamlining-react-component-development-with-a-custom-cli</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Sat, 24 Jun 2023 21:09:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1687640213462/2d63bd5c-c5dd-42b6-8c0d-f9dae26fe40f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>React has become one of the most popular JavaScript libraries for building user interfaces.</p>
<p>As a React developer, I often found myself spending valuable time manually creating components and managing CSS modules.</p>
<p>The lack of consistency and repetitive tasks inspired me to develop a CLI tool that would automate these processes, leading to increased productivity and code quality.</p>
<h2 id="heading-the-inspiration-from-angular-cli">The Inspiration from Angular CLI:</h2>
<p>During my journey of learning Angular, I was impressed by Angular CLI's power and efficiency in generating components and managing project structure.</p>
<p>This inspired me to create a similar CLI tool for React, tailored to my specific needs.</p>
<h3 id="heading-the-pain-points"><strong>The Pain Points</strong></h3>
<p>Before the creation of my React CLI tool, I faced several challenges in my React development workflow:</p>
<ol>
<li><p><strong>Manual Component Creation:</strong> Creating react components with the necessary boilerplate code was time-consuming and error-prone. It often resulted in inconsistencies across different components.</p>
</li>
<li><p><strong>CSS Module Management:</strong> Managing CSS modules for each component was a tedious task. I had to create separate CSS module files, import them into the component files, and ensure consistent naming conventions.</p>
</li>
</ol>
<h3 id="heading-the-birth-of-the-react-cli"><strong>The Birth of the React CLI</strong></h3>
<p>Motivated by my challenges, I embarked on developing a custom CLI tool for React. The goal was to automate component generation, enforce best practices, and improve development efficiency.</p>
<p>Key Features of the React CLI:</p>
<ol>
<li><p><strong>Component Generation:</strong> The CLI allows me to generate React components effortlessly with a single command. It takes the component name from the command and automatically generates the corresponding component file (either <code>.jsx</code> or <code>.tsx</code>) with the required boilerplate code.</p>
</li>
<li><p><strong>CSS Module Integration:</strong> To maintain consistency and avoid naming conflicts, the CLI automatically creates a CSS module file for each component. It associates the CSS module with the component file and ensures a clean separation of styles.</p>
</li>
<li><p><strong>Project Structure Management:</strong> The CLI intelligently detects the project's root directory, ensuring that the generated components are placed correctly within the project structure. It automatically creates the necessary directories, such as <code>src/components</code>, if they don't exist.</p>
</li>
<li><p><strong>TypeScript Support:</strong> The CLI seamlessly handles TypeScript projects by checking for the presence of <code>tsconfig.json</code>. If TypeScript is detected, it generates <code>.tsx</code> components; otherwise, it generates <code>.jsx</code> components.</p>
</li>
</ol>
<h2 id="heading-installation"><strong>Installation</strong></h2>
<p>To use the Rtfc CLI, you can either install it globally or use it with <code>npx</code> without global installation.</p>
<p><strong>Global Installation</strong></p>
<pre><code class="lang-bash">npm install -g rtfc-cli
rtfc-cli g Navbar
</code></pre>
<p><strong>Usage with npx</strong></p>
<pre><code class="lang-bash">npx rtfc-cli generate &lt;componentName&gt;
<span class="hljs-comment"># example</span>
<span class="hljs-comment"># npx rtfc-cli g Navbar</span>
</code></pre>
<p>Replace <code>&lt;componentName&gt;</code> with the desired name of your React component.</p>
<h3 id="heading-future-updates">Future Updates</h3>
<p>To further enhance the React CLI and provide even more value to developers, I have planned the following future updates:</p>
<ol>
<li><p><strong>Class Component Support:</strong> In addition to functional components, I will introduce support for generating class components. This will cater to developers who prefer the class component syntax or have existing codebases using class components.</p>
</li>
<li><p><strong>Next.js Integration:</strong> Next.js is a popular framework for server-rendered React applications. To extend the CLI's compatibility, I will add support for generating components specific to Next.js projects, incorporating Next.js conventions and features.</p>
</li>
</ol>
<p>You can find the React CLI on npm <a target="_blank" href="https://www.npmjs.com/package/rtfc-cli"><strong>here</strong></a> and the GitHub repository <a target="_blank" href="https://github.com/ThePratikSah/rtfc-cli"><strong>here</strong></a>. Feel free to check it out, provide feedback, and contribute to its development.</p>
<p>Thank you ❤️</p>
]]></content:encoded></item><item><title><![CDATA[An introduction to digital ocean functions]]></title><description><![CDATA[Recently I came across a post by the digital ocean where they introduced us to the serverless functions which they recently launched. I'm a huge fan of them in terms of simplicity and pricing. 
I thought of giving it a try and found it to be really e...]]></description><link>https://blog.pratik.dev/an-introduction-to-digital-ocean-functions</link><guid isPermaLink="true">https://blog.pratik.dev/an-introduction-to-digital-ocean-functions</guid><category><![CDATA[DigitalOcean]]></category><category><![CDATA[serverless]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Thu, 26 May 2022 22:25:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1653603506558/C3UZbkjWe.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Recently I came across a post by the digital ocean where they introduced us to the serverless functions which they recently launched. I'm a huge fan of them in terms of simplicity and pricing. </p>
<p>I thought of giving it a try and found it to be really easy to set up and deploy. </p>
<p>In this post, I'll help you in creating your first serverless function on Digital Ocean, how to deploy them and all the necessary steps.</p>
<p>Enjoy the post✌🏻.</p>
<h2 id="heading-getting-started-with-do-functions">🎳 Getting started with DO Functions</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653602768228/paoze-A5s.png" alt="digital ocean functions.png" /></p>
<h3 id="heading-create-a-digital-ocean-account">👤 Create a Digital Ocean account</h3>
<p>If you don't have a digital ocean account, you can create one <a target="_blank" href="https://m.do.co/c/72f15e1dc143">here</a>.
<a target="_blank" href="https://www.digitalocean.com/?refcode=72f15e1dc143&amp;utm_campaign=Referral_Invite&amp;utm_medium=Referral_Program&amp;utm_source=badge"><img src="https://web-platforms.sfo2.digitaloceanspaces.com/WWW/Badge%202.svg" alt="DigitalOcean Referral Badge" /></a></p>
<blockquote>
<p>This link will give you free $100💸 for your testing with a validity of 60 days. You can use this credit for all your tests related to droplets or serverless.</p>
</blockquote>
<p>Once you have the account, we can now move on to installing the <strong>doctl CLI</strong> which will help us in bootstrapping the serverless app.</p>
<h3 id="heading-install-doctl">⬇️ Install doctl</h3>
<p>If you are on a <strong>Mac</strong>, you can install <strong>doctl</strong> with <a target="_blank" href="https://brew.sh/">homebrew</a>. </p>
<pre><code class="lang-bash">brew install doctl
</code></pre>
<p>For <strong>Linux</strong>, you can use <a target="_blank" href="https://snapcraft.io/docs/installing-snapd">Snap Package</a></p>
<pre><code class="lang-bash">sudo snap install doctl
</code></pre>
<p>For <strong>Windows</strong>, you can use the below commands on your Powershell. Open Powershell with <strong>Run as Administrator</strong> </p>
<pre><code class="lang-bash">Invoke-WebRequest https://github.com/digitalocean/doctl/releases/download/v1.76.0/doctl-1.76.0-windows-amd64.zip -OutFile ~\doctl-1.76.0-windows-amd64.zip
</code></pre>
<p>This will download the most recent version of <strong>doctl</strong>. We can now proceed with the unzip of the file.</p>
<pre><code class="lang-bash">Expand-Archive -Path ~\doctl-1.76.0-windows-amd64.zip
</code></pre>
<p>We can now move the <strong>doctl</strong> into a dedicated directory and add it to your system’s path by running:</p>
<pre><code class="lang-bash">New-Item -ItemType Directory <span class="hljs-variable">$env</span>:ProgramFiles\doctl\
Move-Item -Path ~\doctl-1.76.0-windows-amd64\doctl.exe -Destination <span class="hljs-variable">$env</span>:ProgramFiles\doctl\
[Environment]::SetEnvironmentVariable(
    <span class="hljs-string">"Path"</span>,
    [Environment]::GetEnvironmentVariable(<span class="hljs-string">"Path"</span>,
    [EnvironmentVariableTarget]::Machine) + <span class="hljs-string">";<span class="hljs-variable">$env</span>:ProgramFiles\doctl\",
    [EnvironmentVariableTarget]::Machine)
<span class="hljs-variable">$env</span>:Path = [System.Environment]::GetEnvironmentVariable("</span>Path<span class="hljs-string">","</span>Machine<span class="hljs-string">")</span>
</code></pre>
<blockquote>
<p>You can also find a how-to guide 📖 on installing and configuring <strong>doctl</strong> by following this <a target="_blank" href="https://docs.digitalocean.com/reference/doctl/how-to/install/">link</a>.</p>
</blockquote>
<p>Once done, we can now proceed with creating of API Token.</p>
<h3 id="heading-create-an-api-token">🔑 Create an API token</h3>
<p>To generate a personal access token, you first need to log in to your digital ocean <a target="_blank" href="https://cloud.digitalocean.com/">control panel</a>. </p>
<p>Click on the <strong>API</strong> link in the sidebar. When on the <strong>Tokens/Keys</strong> tab of the <strong>Personal access tokens</strong> section, click the <strong>Generate New Token</strong> button.</p>
<p>A New personal access token window will appear.</p>
<p>You can set the name to whatever you want and the same with the expiry of the token. Make sure to give <strong>both read and write access</strong> while generating the token.</p>
<blockquote>
<p>Make sure to copy it safely as it will not be shown again.</p>
</blockquote>
<p>You can also follow <a target="_blank" href="https://docs.digitalocean.com/reference/api/create-personal-access-token/">this link</a> to generate a personal access token on the digital ocean.</p>
<p>We can now proceed with the access token to provide access to <strong>doctl</strong>.</p>
<h3 id="heading-use-api-token-to-grant-account-access-to-doctl">🔓 Use API token to grant account access to doctl</h3>
<p>Run the following command and when prompted, pass the token string. You can also give this auth context a name.</p>
<pre><code class="lang-bash">doctl auth init --context &lt;NAME&gt;
<span class="hljs-comment"># ex doctl auth init --context serverless</span>
</code></pre>
<p>You can add multiple accounts and can switch between auth contexts.</p>
<pre><code class="lang-bash">doctl auth list
doctl auth switch --context &lt;NAME&gt;
</code></pre>
<p>We can now proceed with the validation of the doctl.</p>
<h3 id="heading-validate-if-the-doctl-is-working">✅ Validate if the doctl is working</h3>
<p>You can review your account details by running the following command to confirm you have successfully authorised <strong>doctl</strong>.</p>
<pre><code class="lang-bash">doctl account get
</code></pre>
<p>If authorized successfully, you will get something like this.</p>
<pre><code class="lang-bash">Email                    Droplet Limit    Email Verified    UUID                                    Status
pratik@gmail.com    10               <span class="hljs-literal">true</span>              d0161b45-8c09-4233-dv32-63614c84a0dd    active
</code></pre>
<p>Now we are ready to proceed with installing the support for serverless.</p>
<h3 id="heading-install-support-for-serverless-functions">⬇️ Install support for serverless functions</h3>
<p>To install the support for serverless Functions, we need to install a software extension for that.</p>
<pre><code class="lang-bash">doctl serverless install
</code></pre>
<p>You'll get installation status something like this.</p>
<pre><code class="lang-bash">Downloading...Unpacking...Installing...Cleaning up...
Done
</code></pre>
<p>Next, we need to connect to the development namespace with the following command.</p>
<pre><code class="lang-bash">doctl serverless connect
</code></pre>
<p>It will show the name and API host of your namespace.</p>
<p>We are now ready to proceed with the creation of our first serverless app.</p>
<h3 id="heading-create-a-serverless-app">🖥 Create a serverless app</h3>
<p>Navigate to the directory where you want your functions to stay and then run the following command.</p>
<pre><code class="lang-bash">doctl serverless init --language js do-serverless
</code></pre>
<p>The <strong>-l</strong> or <strong>--language</strong> flag specifies which programming language to use. We have option for <strong>go</strong>, <strong>javascript</strong>, <strong>php</strong>, and <strong>python</strong>.</p>
<p>A directory named <strong>do-serverless</strong> will be created with sample code for "hello world" and configuration files.</p>
<pre><code class="lang-bash">do-serverless/
├── packages
│   └── sample
│       └── hello
│           └── hello.js
└── project.yml
</code></pre>
<p>We don't have to make any changes to the js file, it can be used as it is, we just need to deploy the code to test.</p>
<h3 id="heading-deploy-the-serverless-app">⬆️ Deploy the serverless app</h3>
<p>In order to deploy the serverless code, we need to come out of the directory <code>do-serverless</code> and run the following command.</p>
<pre><code class="lang-bash">doctl serverless deploy do-serverless
</code></pre>
<p>And if you are in the same directory, you can run <code>doctl serverless deploy .</code> </p>
<h3 id="heading-requesting-the-live-url-of-the-function">🔗 Requesting the live URL of the function</h3>
<p>You can request the live URL of the function with the following command.</p>
<pre><code class="lang-bash">doctl sbx fn get sample/hello --url
</code></pre>
<p>This will give you the URL something like this.</p>
<pre><code class="lang-bash">https://faas-blr1-22237d592.doserverless.co/api/v1/web/fn-29f27939-608f-4a63-8b2f-6a35e24c7613/sample/hello
</code></pre>
<p>You can also list all of your deployed functions with the following command.</p>
<pre><code class="lang-bash">doctl serverless <span class="hljs-built_in">functions</span> list
</code></pre>
<pre><code class="lang-bash">Datetime        Access   Kind      Version  Actions
─────────────── ──────── ───────── ──────── ─────────────────────────────────────────────────
05/25 01:56:34  web      nodejs:14 0.0.1    sample/hello
</code></pre>
<h3 id="heading-developing-in-watch-mode">👀 Developing in watch mode</h3>
<p>We can also develop our functions in watch mode as it can speed up our development time as it will keep on watching for code changes and automating build steps.</p>
<p>To develop in watch mode, run the following command:</p>
<pre><code class="lang-bash">doctl serverless watch do-serverless
</code></pre>
<p>When you are done with the development, press <code>CTRL+C</code> to exit the watch mode.</p>
<h3 id="heading-inspecting-the-logs">🕵🏻‍♂️ Inspecting the logs</h3>
<p>We can also see the logs from your functions. Just run the following command.</p>
<pre><code class="lang-bash">doctl serverless activations logs --<span class="hljs-built_in">limit</span> 3
</code></pre>
<p>By default, the limit is 1. We can also add the <code>--follow</code> flag to follow the logs as they are generated.</p>
<p>We can also follow logs from a specific function with the help of the following command.</p>
<pre><code class="lang-bash">doctl serverless activations logs --follow --<span class="hljs-keyword">function</span> sample/hello
</code></pre>
<h2 id="heading-final-thought">❤️ Final thought</h2>
<p>I tried and deployed my function and was able to get a decent response time (~140ms) and this was actually good as compared to <a target="_blank" href="https://firebase.google.com/docs/functions">Firebase Functions</a> which I used in the last project.</p>
<p>Hopefully, I'll try building a couple of projects using DO Functions and see how it performs. So far I really liked how easy was it to set up😀.</p>
<p>You can follow the <a target="_blank" href="https://docs.digitalocean.com/products/">actual doc</a> from the digital ocean for complete information on functions and the official post <a target="_blank" href="https://www.digitalocean.com/blog/introducing-digitalocean-functions-serverless-computing">here</a>.</p>
<p>I hope this post will help you in creating your first serverless function on the digital ocean. If you found this post helpful, please share this post with others and also leave a comment below and let me know your thoughts.</p>
<p>Thanks for the time, see you in my next post.</p>
<p>❤</p>
]]></content:encoded></item><item><title><![CDATA[Handle file uploads in Node JS with Formidable]]></title><description><![CDATA[While handling file uploads via the form in Express, you might have tried Multer. It is good but Formidable is awesome when it comes to simplicity without having to deal with middleware.
The formidable module is used for parsing both the form data an...]]></description><link>https://blog.pratik.dev/handle-file-uploads-in-node-js-with-formidable</link><guid isPermaLink="true">https://blog.pratik.dev/handle-file-uploads-in-node-js-with-formidable</guid><category><![CDATA[Express]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[forms]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Thu, 22 Jul 2021 19:02:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1626980386416/vwS9euYer.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>While handling file uploads via the form in Express, you might have tried Multer. It is good but Formidable is awesome when it comes to simplicity without having to deal with middleware.</p>
<p>The formidable module is used for parsing both the form data and the file uploads. It's very easy to use and can be easily integrated.</p>
<h2 id="installation">Installation</h2>
<p>Visit <strong>npmjs</strong> or click  <a target="_blank" href="https://www.npmjs.com/package/formidable">here</a> or you can install the package by using the below command.</p>
<pre><code><span class="hljs-built_in">npm</span> i formidable
</code></pre><p>The highlights of this module are (according to <strong>npmjs</strong>): </p>
<ul>
<li>Fast (~900-2500 MB/sec) &amp; streaming multipart parser</li>
<li>Low memory footprint</li>
<li>Graceful error handling</li>
<li>Very high test coverage</li>
</ul>
<h3 id="appjs">app.js</h3>
<pre><code><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>)
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">"fs"</span>);
<span class="hljs-keyword">const</span> formidable = <span class="hljs-built_in">require</span>(<span class="hljs-string">"formidable"</span>);

<span class="hljs-keyword">const</span> app = express();

app.post(<span class="hljs-string">"/handle-uploads"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> form = formidable();
  form.parse(req, <span class="hljs-keyword">async</span> (err, fields, files) =&gt; {
    <span class="hljs-comment">// your form fields will be found inside 'fields' variable</span>
    <span class="hljs-comment">// your form files will be inside files variable</span>
  });
});

app.listen(<span class="hljs-number">3300</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-built_in">console</span>.log(err);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Server started on port 3300"</span>);
});
</code></pre><p>Let's say we want to upload the file to a particular location suppose inside the <strong>uploads</strong> directory. </p>
<p>For that, we have to specify the path inside <code>form.parse()</code>.</p>
<pre><code><span class="hljs-comment">// inside app.post("/handle-uploads", (req, res) =&gt; {</span>

<span class="hljs-keyword">const</span> form = formidable();
form.parse(req, <span class="hljs-keyword">async</span> (err, fields, files) =&gt; {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).json({
      <span class="hljs-attr">status</span>: <span class="hljs-string">"Failure"</span>,
      <span class="hljs-attr">msg</span>: <span class="hljs-string">"Some error occured "</span> + err.message,
    });
  }
  <span class="hljs-keyword">let</span> oldPath = files.nameOfTheField.path;
  <span class="hljs-keyword">let</span> newPath = <span class="hljs-string">`./uploads/<span class="hljs-subst">${files.nameOfTheField.name}</span>`</span>;
  fs.rename(oldPath, newPath, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).json({
        <span class="hljs-attr">status</span>: <span class="hljs-string">"Failure"</span>,
        <span class="hljs-attr">msg</span>: <span class="hljs-string">"Failed to upload file. "</span> + err.message,
      });
    }
    res.status(<span class="hljs-number">201</span>).json({
      <span class="hljs-attr">status</span>: <span class="hljs-string">"Success"</span>, 
      <span class="hljs-attr">msg</span>: <span class="hljs-string">"File uploaded successfully"</span>
    });
  });
});
</code></pre><h2 id="thanks">Thanks</h2>
<p>I hope this post will help you in handling file uploads easily. If you found this code helpful, please share this post with others and also leave a comment below and let me know your thoughts.</p>
<p>Thanks for the time, see you in my next post.</p>
<p>❤</p>
]]></content:encoded></item><item><title><![CDATA[Log your Node Js error in a log file like a PRO!]]></title><description><![CDATA[We all have used console.log() at some point in time but these are just for debugging purpose only. It's not recommended in a production-level app.
If you'll use them in your production level app, this may not help you in finding the exact error and ...]]></description><link>https://blog.pratik.dev/log-your-node-js-error-in-a-log-file</link><guid isPermaLink="true">https://blog.pratik.dev/log-your-node-js-error-in-a-log-file</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Express]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Tue, 30 Mar 2021 19:35:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1617132228575/bG_huBcQs.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We all have used <code>console.log()</code> at some point in time but these are just for debugging purpose only. It's not recommended in a production-level app.</p>
<p>If you'll use them in your production level app, this may not help you in finding the exact error and when did that occur.</p>
<p>To have a proper track of your errors, we must use something reliable so that we can check for our error later.</p>
<p>One of the best way to identify all of your error is to make a log file for all of your errors.</p>
<blockquote>
<p>But hey, how will I create log files for all of my future errors?</p>
</blockquote>
<p>I was working on my office project where I learnt that it's quite easy to implement, all thanks to <a target="_blank" href="https://www.linkedin.com/in/vibhor-bakshi-022632157/">Vibhor sir</a>.</p>
<p>Don't worry. You don't have to create log files for your errors manually.</p>
<p><strong>The best thing about Node js is that it has packages for everything you can think of😉. </strong></p>
<h2 id="using-winston">Using Winston</h2>
<p><a target="_blank" href="https://www.npmjs.com/package/winston">Winston</a> makes it super easy in logging your errors. With over <strong>6,155,906</strong> installs each week, you can think how much power it has.</p>
<p>You can easily implement it in your code.</p>
<p><strong>Start by installing Winston</strong></p>
<pre><code><span class="hljs-built_in">npm</span> i winston
</code></pre><p>We, need another package to have our logs rotated at a particular interval. Logs can be rotated based on a date, size limit, and old logs can be removed based on the count of elapsed days.</p>
<pre><code><span class="hljs-built_in">npm</span> i winston-daily-rotate-file
</code></pre><p>The DailyRotateFile transport can rotate files by minute, hour, day, month, year or weekday. </p>
<p>The next step is to set up the code for <code>Winston</code>.</p>
<p>Let's create a file for Winston. You can name it whatever you want. </p>
<p>I'll be naming <code>logger.js</code></p>
<pre><code><span class="hljs-keyword">const</span> winston = <span class="hljs-built_in">require</span>(<span class="hljs-string">"winston"</span>);
<span class="hljs-built_in">require</span>(<span class="hljs-string">"winston-daily-rotate-file"</span>);

<span class="hljs-keyword">const</span> dashLog = <span class="hljs-keyword">new</span> winston.transports.DailyRotateFile({
  filename: <span class="hljs-string">"./logs/dash-%DATE%.log"</span>,
  datePattern: <span class="hljs-string">"YYYY-MM-DD"</span>,
  zippedArchive: <span class="hljs-literal">true</span>,
  maxSize: <span class="hljs-string">"20m"</span>,
});

<span class="hljs-keyword">const</span> dash = winston.createLogger({
  transports: [
    dashLog,
    <span class="hljs-keyword">new</span> winston.transports.Console({
      colorize: <span class="hljs-literal">true</span>,
    }),
  ],
});

<span class="hljs-built_in">module</span>.<span class="hljs-built_in">exports</span> = {
  dashLogger: dash,
};
</code></pre><p>Some of the options which I've used here are filename, datePattern, zippedArchive, maxSize.</p>
<p><strong><code>filename</code></strong>: This will let you name your log files the way you want.</p>
<p><strong><code>datePattern</code></strong>: It is used to dictate the frequency of the file rotation.</p>
<p><strong><code>zippedArchive</code></strong>: A boolean to define whether or not to gzip archived log files. (default: 'false')</p>
<p><strong><code>maxSize</code></strong>: Maximum size of the file after which it will rotate.</p>
<p>Now, open your starting file of node js. Mine is <code>app.js</code></p>
<p>To use this logger, we just need to import our <code>logger.js</code> file and instead of using <code>console.log()</code>, we can use our custom logger.</p>
<p>In our <code>app.js</code></p>
<pre><code><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);

<span class="hljs-keyword">const</span> { dashLogger } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./logger"</span>);

<span class="hljs-keyword">const</span> app = express();

app.use(express.json());

app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">return</span> res.render(<span class="hljs-string">"view"</span>, {
      data,
    });
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
    dashLogger.error(<span class="hljs-string">`Error : <span class="hljs-subst">${error}</span>,Request : <span class="hljs-subst">${req.originalUrl}</span>`</span>);
    res.render(<span class="hljs-string">"400"</span>);
  }
});

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Server started"</span>);
});
</code></pre><p>What we have done here is that we are wrapping our code in a try-catch block and if it throws an error, our logger will create a log file inside of the <code>logs</code> directory.</p>
<blockquote>
<p>Here, I've also kept <code>req.originalUrl</code> so that it would be easy to detect where is the actual point of error. It will log the error with the actual route.</p>
</blockquote>
<p>In this way, we can easily have the logs of our application and it will help us in finding the error easily.</p>
<h3 id="thanks">Thanks</h3>
<p>I hope this post will help you in debugging your code much easier. If you found this code helpful and the logger actually helped you at any point of time, just leave a comment below and let me know.</p>
<p>Thanks for the time, see you in my next post.</p>
<p>❤</p>
]]></content:encoded></item><item><title><![CDATA[Let's create a dictionary with vanilla javascript]]></title><description><![CDATA[Hi, welcome back. Last night I was making a video for my Javascript playlist and it was the last video of the playlist where I taught how to make a dictionary using vanilla javascript.
Creating your own database for storing all the words and their me...]]></description><link>https://blog.pratik.dev/lets-create-a-dictionary-with-vanilla-javascript</link><guid isPermaLink="true">https://blog.pratik.dev/lets-create-a-dictionary-with-vanilla-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><category><![CDATA[CSS3]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Wed, 20 Jan 2021 08:20:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1611130626276/BlHqeLalo.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hi, welcome back. Last night I was making a video for my Javascript playlist and it was the last video of the playlist where I taught how to make a dictionary using vanilla javascript.</p>
<p>Creating your own database for storing all the words and their meanings can be quite a difficult task. The best way which I found was to use any dictionary API available in the market.</p>
<p>I tried searching a lot and found one API which a developer has made available for free.</p>
<p><a target="_blank" href="https://dictionaryapi.dev/">https://dictionaryapi.dev/</a></p>
<p>Now, that we have the API, we'll test this API first and then we'll implement this API in our code.</p>
<blockquote>
<p>BTW, here is the final version of the <a target="_blank" href="https://dictionary.vercel.app/">project</a>.</p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://dictionary.vercel.app/">https://dictionary.vercel.app/</a></div>
<p>I've hosted the app on <a target="_blank" href="https://vercel.com/">Vercel</a> and the platform is super easy to deploy your projects for free and it also comes with CI/CD which makes updating your application super easy and fast.</p>
<h2 id="lets-start">Let's start</h2>
<p>Open your browser and go to this <a target="_blank" href="https://dictionaryapi.dev/">link</a>. This is the homepage of the API we are going to use.</p>
<p>Copy the link provided or use the below link.</p>
<pre><code><span class="hljs-symbol">https:</span>/<span class="hljs-regexp">/api.dictionaryapi.dev/api</span><span class="hljs-regexp">/v2/entries</span><span class="hljs-regexp">/&lt;language_code&gt;/</span>&lt;word&gt;
</code></pre><p>Change the language_code to the language of your choice (See the list of supported languages in the docs).</p>
<pre><code><span class="hljs-symbol">https:</span>/<span class="hljs-regexp">/api.dictionaryapi.dev/api</span><span class="hljs-regexp">/v2/entries</span><span class="hljs-regexp">/en/</span>&lt;word&gt;

<span class="hljs-comment"># I have changed it to en for English</span>
</code></pre><p>Replace <code>&lt;word&gt;</code> with the word whose meaning you want to find. </p>
<pre><code><span class="hljs-symbol">https:</span>/<span class="hljs-regexp">/api.dictionaryapi.dev/api</span><span class="hljs-regexp">/v2/entries</span><span class="hljs-regexp">/en/programmer</span>

<span class="hljs-comment"># this is how the API has to be used</span>
</code></pre><p>Once you'll hit this URL in your browser, you'll get the JOSN response something like this.</p>
<pre><code>[
  {
    <span class="hljs-attr">"word"</span>: <span class="hljs-string">"programmer"</span>,
    <span class="hljs-attr">"phonetics"</span>: [
      {
        <span class="hljs-attr">"text"</span>: <span class="hljs-string">"/ˈproʊˌɡræmər/"</span>,
        <span class="hljs-attr">"audio"</span>: <span class="hljs-string">"https://lex-audio.useremarkable.com/mp3/programmer_us_1.mp3"</span>,
      }
    ],
    <span class="hljs-attr">"meanings"</span>: [
      {
        <span class="hljs-attr">"partOfSpeech"</span>: <span class="hljs-string">"noun"</span>,
        <span class="hljs-attr">"definitions"</span>: [
          {
            <span class="hljs-attr">"definition"</span>: <span class="hljs-string">"A person who writes computer programs."</span>,
            <span class="hljs-attr">"example"</span>: <span class="hljs-string">"computer programmers and analysts"</span>
          }
        ]
      }
    ]
  }
]
</code></pre><p>From the response, we can easily extract the required data and populate in our HTML elements.</p>
<h2 id="making-request-using-fetch">Making request using <code>fetch()</code></h2>
<p>When we try to make any request to any endpoint, <code>fetch()</code> returns a promise. To handle the promise, either we can use <code>.then().catch()</code> or we can use <code>async-await</code>.</p>
<p>Here, I've used <code>async</code> <code>await</code>.</p>
<p>Below is the code for making the request.</p>
<pre><code><span class="hljs-comment">// I've made the function async</span>
<span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> (word) =&gt; {

  <span class="hljs-comment">// make a req to the api</span>
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> fetch(
    `https:<span class="hljs-comment">//api.dictionaryapi.dev/api/v2/entries/en/${word}`</span>
  );

  <span class="hljs-keyword">if</span> (!result.ok) {
    alert(<span class="hljs-string">"No definition found"</span>);
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> result.json();

};
</code></pre><p><strong>Here is the HTML code</strong></p>
<pre><code><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Dictionary App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"h1"</span>&gt;</span>Dictionary App<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">onkeypress</span>=<span class="hljs-string">"handle(event)"</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
          <span class="hljs-attr">class</span>=<span class="hljs-string">"search-field"</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Type and press enter"</span>
        /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"result"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"word"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"phonetics"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">audio</span>
          <span class="hljs-attr">src</span>=<span class="hljs-string">""</span>
          <span class="hljs-attr">controls</span>
        &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">audio</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"wordmeaning"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"word-definition"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"wordmeaning"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"synonyms"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./app.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre><p>We have some text elements and a search field. For the styling part, you can use your own custom CSS or you can use the CSS code provided below.</p>
<p><strong>CSS</strong></p>
<pre><code>* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}

<span class="hljs-selector-pseudo">::-webkit-scrollbar</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">10px</span>;
}

<span class="hljs-selector-pseudo">::-webkit-scrollbar-track</span> {
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#f1a576</span>;
}

<span class="hljs-selector-pseudo">::-webkit-scrollbar-thumb</span> {
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#e47632</span>;
}

<span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#ffc5a1</span>;
}

<span class="hljs-selector-class">.h1</span> {
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">300</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">15px</span>;
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">"Segoe UI"</span>, Roboto, Oxygen,
    Ubuntu, Cantarell, <span class="hljs-string">"Open Sans"</span>, <span class="hljs-string">"Helvetica Neue"</span>, sans-serif;
}

<span class="hljs-selector-class">.search-field</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">500px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#1e1e1e</span>;
  <span class="hljs-attribute">outline</span>: none;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#1e1e1e</span>;
}

<span class="hljs-selector-class">.result</span> {
  <span class="hljs-attribute">display</span>: none;
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">500px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">500px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">30px</span>;
  <span class="hljs-attribute">overflow-y</span>: scroll;
  <span class="hljs-attribute">border-left</span>: <span class="hljs-number">5px</span> solid <span class="hljs-number">#e66a1e</span>;
}

<span class="hljs-selector-class">.result</span> &gt; <span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">40px</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">300</span>;
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">"Segoe UI"</span>, Roboto, Oxygen,
    Ubuntu, Cantarell, <span class="hljs-string">"Open Sans"</span>, <span class="hljs-string">"Helvetica Neue"</span>, sans-serif;
  <span class="hljs-attribute">display</span>: inline;
}

<span class="hljs-selector-class">.wordmeaning</span> {
  <span class="hljs-attribute">display</span>: inline-block;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">24px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">"Segoe UI"</span>, Roboto, Oxygen,
    Ubuntu, Cantarell, <span class="hljs-string">"Open Sans"</span>, <span class="hljs-string">"Helvetica Neue"</span>, sans-serif;
}

<span class="hljs-selector-class">.phonetics</span> {
  <span class="hljs-attribute">display</span>: inline-block;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#ffc5a1</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">5px</span> <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">600</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">"Segoe UI"</span>, Roboto, Oxygen,
    Ubuntu, Cantarell, <span class="hljs-string">"Open Sans"</span>, <span class="hljs-string">"Helvetica Neue"</span>, sans-serif;
}

<span class="hljs-selector-class">.result</span> &gt; <span class="hljs-selector-tag">audio</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">outline</span>: none;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.word-definition</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">28px</span>;
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">"Segoe UI"</span>, Roboto, Oxygen,
    Ubuntu, Cantarell, <span class="hljs-string">"Open Sans"</span>, <span class="hljs-string">"Helvetica Neue"</span>, sans-serif;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">500</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.synonyms</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">22px</span>;
  <span class="hljs-attribute">flex-direction</span>: row;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
}

<span class="hljs-selector-class">.pills</span> {
  <span class="hljs-attribute">margin-right</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">5px</span> <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">"Segoe UI"</span>, Roboto, Oxygen,
    Ubuntu, Cantarell, <span class="hljs-string">"Open Sans"</span>, <span class="hljs-string">"Helvetica Neue"</span>, sans-serif;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#ffc5a1</span>;
}

<span class="hljs-comment">/* your media query here */</span>
<span class="hljs-keyword">@media</span> <span class="hljs-keyword">only</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">500px</span>) {
  <span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
  }
  <span class="hljs-selector-class">.search-field</span>,
  <span class="hljs-selector-class">.result</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  }
}
</code></pre><p>I've tried to make the app responsive for mobile as well. </p>
<p><strong>Now the Javascript</strong></p>
<pre><code><span class="hljs-keyword">const</span> resultDiv = <span class="hljs-built_in">document</span>.<span class="hljs-built_in">querySelector</span>(<span class="hljs-string">".result"</span>);
<span class="hljs-keyword">const</span> wordEle = <span class="hljs-built_in">document</span>.<span class="hljs-built_in">querySelector</span>(<span class="hljs-string">".word"</span>);
<span class="hljs-keyword">const</span> phonetics = <span class="hljs-built_in">document</span>.<span class="hljs-built_in">querySelector</span>(<span class="hljs-string">".phonetics"</span>);
<span class="hljs-keyword">const</span> audio = <span class="hljs-built_in">document</span>.<span class="hljs-built_in">querySelector</span>(<span class="hljs-string">"audio"</span>);
<span class="hljs-keyword">const</span> wordMeaning = <span class="hljs-built_in">document</span>.<span class="hljs-built_in">querySelector</span>(<span class="hljs-string">".word-definition"</span>);
<span class="hljs-keyword">const</span> synonyms = <span class="hljs-built_in">document</span>.<span class="hljs-built_in">querySelector</span>(<span class="hljs-string">".synonyms"</span>);

<span class="hljs-comment">// function to handle all the word</span>
<span class="hljs-keyword">const</span> handle = <span class="hljs-keyword">async</span> (e) =&gt; {
  <span class="hljs-keyword">if</span> (e.keyCode === <span class="hljs-number">13</span>) {
    <span class="hljs-keyword">const</span> word = e.target.value;
    <span class="hljs-comment">// make a req to the api</span>
    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> fetch(
      `https:<span class="hljs-comment">//api.dictionaryapi.dev/api/v2/entries/en/${word}`</span>
    );
    <span class="hljs-keyword">if</span> (!result.ok) {
      alert(<span class="hljs-string">"No definition found"</span>);
      <span class="hljs-keyword">return</span>;
    }
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> result.json();
    resultDiv.style.display = <span class="hljs-string">"block"</span>;
    wordEle.innerText = data[<span class="hljs-number">0</span>].word;
    phonetics.innerText = data[<span class="hljs-number">0</span>].phonetics[<span class="hljs-number">0</span>].text;
    audio.src = data[<span class="hljs-number">0</span>].phonetics[<span class="hljs-number">0</span>].audio;
    wordMeaning.innerText = data[<span class="hljs-number">0</span>].meanings[<span class="hljs-number">0</span>].definitions[<span class="hljs-number">0</span>].definition;
    <span class="hljs-keyword">const</span> synonymsArray = data[<span class="hljs-number">0</span>].meanings[<span class="hljs-number">0</span>].definitions[<span class="hljs-number">0</span>].synonyms;
    <span class="hljs-keyword">if</span> (synonymsArray) {
      let synonymsData = <span class="hljs-string">""</span>;
      <span class="hljs-keyword">for</span> (let i = <span class="hljs-number">0</span>; i &lt; synonymsArray.length; i++) {
        synonymsData += `&lt;p <span class="hljs-class"><span class="hljs-keyword">class</span>="<span class="hljs-title">pills</span>"&gt;$</span>{synonymsArray[i]}&lt;/p&gt;`;
      }
      synonyms.innerHTML = synonymsData;
    } <span class="hljs-keyword">else</span> {
      synonyms.innerHTML = <span class="hljs-string">'&lt;p class="pills"&gt;No synonyms available&lt;/p&gt;'</span>;
    }
  }
};
</code></pre><p>Now, push the code to Github and from there you can connect your Github to Vercel and you can deploy your app in one <a target="_blank" href="https://vercel.com/docs">click</a>.</p>
<p>Well, this was all for today's post and if you found it helpful, please leave a like &amp; comment.</p>
<p>Thanks for your time and I'll meet you in my next post. Take care and happy coding🙂!</p>
]]></content:encoded></item><item><title><![CDATA[Getting started with useState hook in React JS]]></title><description><![CDATA[Hooks are a new concept in React 16.8 (current version is 17.0.1 as on Nov 26, 2020). It helps us in using the state in your component without writing the class. This post will help you in getting started with Hooks in React Js.
What is Hooks in Reac...]]></description><link>https://blog.pratik.dev/getting-started-with-hooks-in-react-js</link><guid isPermaLink="true">https://blog.pratik.dev/getting-started-with-hooks-in-react-js</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Thu, 26 Nov 2020 17:09:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607792961666/o9QO2NCxi.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hooks are a new concept in React 16.8 (current version is 17.0.1 as on Nov 26, 2020). It helps us in using the <strong><a target="_blank" href="https://reactjs.org/docs/state-and-lifecycle.html">state</a></strong> in your component without writing the class. This post will help you in getting started with Hooks in React Js.</p>
<h2 id="what-is-hooks-in-react">What is Hooks in React?</h2>
<p>Hooks are the concept in React, which allows you to use states and some other features of React which was earlier available only in the class-based component.</p>
<p>So, after the introduction of Hooks in React, you'll be able to use the state and some other features inside your <strong>functional component, </strong>which was not possible earlier without writing class-based components.</p>
<p>One of the best examples of hooks in react is <strong>useState</strong> function.</p>
<h2 id="the-usestate-hook">The useState hook</h2>
<p>State in react holds the property value in a component. When the state changes, the component re-renders.</p>
<p>To use states in our functional component, we use the <strong>useState</strong> hook and, it helps us to eliminate the use of class in our code.</p>
<p>Unlike class, the state shouldn't have to be an object while using <strong>useState</strong> hook. It can contain any data type.</p>
<p>The <strong>useState</strong> method takes an initial value of state as the parameter and, it returns an array which contains two elements, <strong>the initial value of the state</strong> and <strong>a function to make changes or modify the state's initial value</strong>.</p>
<p>Let's see <strong>useState</strong> hook in action.</p>
<pre><code><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Declare a new state variable, which we'll call "count"</span>
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>You clicked {count} times<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}&gt;
        Click me
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre><p>Here the <code>useState</code> will return two value, one is the initial value of <code>count</code> and another is <code>function</code> to change the value of <code>count</code>.</p>
<p>Now we are able to use the variable <code>count</code> inside the <code>p</code> tag. It will show the value of count instead of the text count.</p>
<pre><code><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>You clicked {count} times.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre><p>Since the initial value of our count is <code>0</code>, it will show, <code>You clicked 0 times.</code></p>
<p>Now, we are calling the <code>setCount</code> method inside the <code>onClick</code> of the button and we are incrementing the value of the count once the button is pressed.</p>
<p>This will increment the value of the count and will update the UI.</p>
<p>This was all about <strong>useState</strong> Hook in a react app'. If you found my application helpful, please mark <strong>recommend</strong> below in the comments section below.</p>
<p>I hope you liked my post on <strong>Getting started with useState hook in React JS </strong>and if you found my post helpful, please share it with your friends and if you have any doubt, feel free to comment below and I'll try to solve your problem ASAP.</p>
<p>Thanks for your time and I'll meet you in my next post. Take care and happy coding🙂!</p>
]]></content:encoded></item><item><title><![CDATA[Login with Google in React JS]]></title><description><![CDATA[In my last post, we learnt how to use google sign-in in a PHP app and hope you all liked it. In this post, we are going to see how to log in with Google in a react app.
All you need is Google API Credential and react-google-login package which you ca...]]></description><link>https://blog.pratik.dev/login-with-google-in-react-js</link><guid isPermaLink="true">https://blog.pratik.dev/login-with-google-in-react-js</guid><category><![CDATA[React]]></category><category><![CDATA[Google]]></category><category><![CDATA[oauth]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Wed, 04 Nov 2020 17:03:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607792634565/sttWgUm5c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In my last post, we learnt how to use google sign-in in a PHP app and hope you all liked it. In this post, we are going to see how to log in with Google in a react app.</p>
<p>All you need is <strong><a target="_blank" href="https://console.developers.google.com/">Google API Credential</a></strong> and <strong><a target="_blank" href="https://www.npmjs.com/package/react-google-login">react-google-login</a></strong> package which you can install using <strong>NPM</strong>.</p>
<blockquote>
<p><strong>Update</strong>: <a target="_blank" href="https://reactgoogle.netlify.app/">Here is the live link to the app what we are going to make.</a></p>
</blockquote>
<h3 id="google-api-credentials">Google API Credentials</h3>
<p>We'll start by getting Google API keys and, for this, you need a google account which I hope we all have one.</p>
<p>Now, go to the below URL and sign in there.
<a target="_blank" href="https://console.developers.google.com/">Google Cloud Platform</a></p>
<p>Here, you need to click on the<strong> Create Project </strong>button. It'll ask you to enter a name for your project.</p>
<p>Enter any name for your project and click <strong>Create</strong>.</p>
<p>Now go to the homepage of <a target="_blank" href="https://console.developers.google.com/">Google Console</a> and from the menu on your left side of the screen, click on <strong>OAuth consent screen</strong>. Make sure your project is selected which you have created just now.</p>
<p>Give your application a name and click save. It will redirect to a new page and, it will ask you to <strong>Create Credentials</strong>.</p>
<p>Click on that and select <strong>OAuth client ID</strong> from the dropdown.</p>
<p>It will ask you for the <strong>application type. </strong> Select the Web application and hit <strong>Create.</strong></p>
<p>Give it a name and a redirect URL.</p>
<p><code>http://localhost:3000/</code></p>
<p>All done. It will provide you with your <strong>client id</strong> and <strong>client secret key</strong>.</p>
<p>You are now done with the <strong>Google API Credentials </strong>part.</p>
<p>Let us now install <strong>react-google-login </strong>package.</p>
<p>To install the package, type the below command in your terminal and hit enter and it will install the package.</p>
<pre><code>npm i react-google-<span class="hljs-keyword">login</span>
</code></pre><p>Once the package is installed, we can now move to the code part.</p>
<p>We need to create two <strong>components </strong>in our <code>src</code> directory.</p>
<ol>
<li><code>Login.jsx</code></li>
<li><code>Logout.jsx</code></li>
<li><code>Profile.jsx</code></li>
</ol>
<p>Let's see the login component.</p>
<p>Inside your <code>Login.jsx</code> file, paste the following code.</p>
<blockquote>
<p>Don't forget to replace the client id in both the components with your client id.</p>
</blockquote>
<pre><code><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { GoogleLogin } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-google-login"</span>;

<span class="hljs-keyword">const</span> clientId = 
      <span class="hljs-string">"your-client-id-here.apps.googleusercontent.com"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Login</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onSuccess</span>(<span class="hljs-params">res</span>) </span>{
    props.setUser(res.profileObj);
  }
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onFailure</span>(<span class="hljs-params">res</span>) </span>{
    <span class="hljs-comment">// console.log(res);</span>
    alert(<span class="hljs-string">`Oops! Some error occured: <span class="hljs-subst">${res}</span>`</span>);
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">GoogleLogin</span>
        <span class="hljs-attr">clientId</span>=<span class="hljs-string">{clientId}</span>
        <span class="hljs-attr">buttonText</span>=<span class="hljs-string">"Login"</span>
        <span class="hljs-attr">onSuccess</span>=<span class="hljs-string">{onSuccess}</span>
        <span class="hljs-attr">onFailure</span>=<span class="hljs-string">{onFailure}</span>
        <span class="hljs-attr">cookiePolicy</span>=<span class="hljs-string">{</span>"<span class="hljs-attr">single_host_origin</span>"}
        <span class="hljs-attr">isSignedIn</span>=<span class="hljs-string">{true}</span>
      /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Login;
</code></pre><p>We are done with the login part and we can now move to the logout part. Below is the code for the logout component. Paste the below code in your <code>Logout.jsx</code> file.</p>
<pre><code><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { GoogleLogout } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-google-login"</span>;

<span class="hljs-keyword">const</span> clientId =
      <span class="hljs-string">"your-client-id-here.apps.googleusercontent.com"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Logout</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onSuccess</span>(<span class="hljs-params">res</span>) </span>{
    props.setUser(<span class="hljs-literal">null</span>);
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">GoogleLogout</span>
        <span class="hljs-attr">clientId</span>=<span class="hljs-string">{clientId}</span>
        <span class="hljs-attr">buttonText</span>=<span class="hljs-string">"Logout"</span>
        <span class="hljs-attr">onLogoutSuccess</span>=<span class="hljs-string">{onSuccess}</span>
      /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Logout;
</code></pre><p>We are done with the login and logout component and we are left with the Profile component. Create a new file named <code>Component.jsx</code> and paste the below code.</p>
<pre><code><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> Logout <span class="hljs-keyword">from</span> <span class="hljs-string">"./Logout"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"../stylesheet/Profile.css"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Profile</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"profile-card"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{props.user.imageUrl}</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{props.user.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>{props.user.email}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Id: {props.user.googleId}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Logout</span> <span class="hljs-attr">setUser</span>=<span class="hljs-string">{props.setUser}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Profile;
</code></pre><p>Now we need to import both login and profile components in our app component.
Here is the code for <code>App.js</code> file. Paste this code in your <code>App.js</code> file.</p>
<pre><code><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> Login <span class="hljs-keyword">from</span> <span class="hljs-string">"./Login"</span>;
<span class="hljs-keyword">import</span> Profile <span class="hljs-keyword">from</span> <span class="hljs-string">"./Profile"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"../stylesheet/App.css"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [user, setUser] = useState(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"app"</span>&gt;</span>
      {user ? (
        <span class="hljs-tag">&lt;<span class="hljs-name">Profile</span> <span class="hljs-attr">user</span>=<span class="hljs-string">{user}</span> <span class="hljs-attr">setUser</span>=<span class="hljs-string">{setUser}</span> /&gt;</span>
      ) : (
        <span class="hljs-tag">&lt;<span class="hljs-name">Login</span> <span class="hljs-attr">setUser</span>=<span class="hljs-string">{setUser}</span> /&gt;</span>
      )}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre><h3 id="lets-understand-the-code">Let's understand the code</h3>
<p>Now, what is happening here is we are creating a <strong>user </strong>state and storing the user profile object in it once the user is logged in.</p>
<pre><code>  const [<span class="hljs-keyword">user</span>, setUser] = useState(<span class="hljs-keyword">null</span>);
</code></pre><p>In my both login and profile component, I'm passing setUser as a prop so that I can update the user when the user tries to log in and when a user tries to logout in profile component, I'm setting the user state to null.</p>
<p>The ternary operator is helping me to render content conditionally and if you are not familiar with conditional rendering then you can take reference from my post on conditional rendering here.</p>
<p><a target="_blank" href="/render-content-conditionally-in-react-js/">How to render content conditionally in React JS</a></p>
<p>I know this is not the best-looking sign-in page but this post is not about CSS styling. If you want to style your index page, you can do by adding a stylesheet named <code>App.css</code> in the same directory and paste the below code.</p>
<pre><code><span class="hljs-selector-class">.app</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">justify-content</span>: center;
}
</code></pre><p>Now we are done with the App.css and we need to style our Profile card. Here is the code for the <code>Profile.css</code>. Copy the below code and paste the code in your <code>Profile.css</code> stylesheet.</p>
<pre><code><span class="hljs-selector-class">.profile-card</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">300px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">400px</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">252</span>, <span class="hljs-number">231</span>, <span class="hljs-number">231</span>);
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
}

<span class="hljs-selector-class">.profile-card</span> &gt; <span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50%</span>;
}

<span class="hljs-selector-class">.profile-card</span> &gt; <span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">87</span>, <span class="hljs-number">87</span>, <span class="hljs-number">87</span>);
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">22px</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">500</span>;
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">"Segoe UI"</span>, Roboto, Oxygen,
    Ubuntu, Cantarell, <span class="hljs-string">"Open Sans"</span>, <span class="hljs-string">"Helvetica Neue"</span>, sans-serif;
}

<span class="hljs-selector-class">.profile-card</span> &gt; <span class="hljs-selector-tag">span</span> {
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">"Segoe UI"</span>, Roboto, Oxygen,
    Ubuntu, Cantarell, <span class="hljs-string">"Open Sans"</span>, <span class="hljs-string">"Helvetica Neue"</span>, sans-serif;
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">77</span>, <span class="hljs-number">77</span>, <span class="hljs-number">77</span>);
}

<span class="hljs-selector-class">.profile-card</span> &gt; <span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">"Segoe UI"</span>, Roboto, Oxygen,
    Ubuntu, Cantarell, <span class="hljs-string">"Open Sans"</span>, <span class="hljs-string">"Helvetica Neue"</span>, sans-serif;
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">36</span>, <span class="hljs-number">36</span>, <span class="hljs-number">36</span>);
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">12px</span>;
}
</code></pre><p>Now, we are done with the login. If you want to test the link, open your terminal and run the below command in your terminal.</p>
<pre><code>npm <span class="hljs-keyword">start</span>    
</code></pre><p>This will start your app and will open the URL in your default browser.</p>
<p>Use any of your Gmail and it will log you in and will show you email in the alert box.</p>
<p>This was all about how to use 'login with Google in a react app'. Here is the link to the GitHub repo for the complete source code.</p>
<p><a target="_blank" href="https://github.com/ThePratikSah/login-with-google-react-app">ThePratikSah/login-with-google-react-app</a></p>
<p>If you found my application helpful, please star my repo on GitHub.</p>
<p>I hope you liked my post on <strong>Log in with Google in a React App </strong>and if you found my post helpful, please share it with your friends and if you have any doubt, feel free to comment below and I'll try to solve your problem ASAP.</p>
<p>Thanks for your time and I'll meet you in my next post. Take care and happy coding🙂!</p>
]]></content:encoded></item><item><title><![CDATA[Login with Google in a PHP web app]]></title><description><![CDATA[We all have used Google Login at some point of time whether in any android app or in any web app. 
It is one of the easiest ways to onboard any user into your app. You just need a single click and with your Google account, the user can easily login o...]]></description><link>https://blog.pratik.dev/login-with-google-in-a-php-web-app</link><guid isPermaLink="true">https://blog.pratik.dev/login-with-google-in-a-php-web-app</guid><category><![CDATA[oauth]]></category><category><![CDATA[Google]]></category><category><![CDATA[PHP]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Thu, 15 Oct 2020 16:57:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607792328616/MFNYEcRvL.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We all have used Google Login at some point of time whether in any android app or in any web app. </p>
<p>It is one of the easiest ways to onboard any user into your app. You just need a single click and with your Google account, the user can easily login or signup in your website.</p>
<p>In today's post, I'll be showing you how you can use Google Sign-in on your PHP website. All you need is <strong><a target="_blank" href="https://console.developers.google.com/">Google API Credential</a></strong>and Google API Client Library for PHP which you can install using composer. </p>
<h3 id="google-api-credentials">Google API Credentials</h3>
<p>We'll start by getting Google API keys and for this, you need a google account and I hope we all have one.</p>
<p>Now, go to the below URL and sign in there.</p>
<p><a target="_blank" href="https://console.developers.google.com/">Google Cloud Platform</a></p>
<p>Here, you need to click on <strong>Create Project </strong> button. It'll ask you to enter a name for your project. </p>
<p>Enter any name for your project and click <strong>Create</strong>.</p>
<p>Now go to the homepage of <a target="_blank" href="https://console.developers.google.com/">Google Console</a> and from the menu on your left side of the screen, click on <strong>OAuth consent screen</strong>. Make sure your project is selected which you have created just now.</p>
<p>Give your application a name and click save. It will redirect to a new page and it will ask you to <strong>Create Credentials</strong>.</p>
<p>Click on that and select <strong>OAuth client ID</strong> from the dropdown.</p>
<p>It will ask you for <strong>application type. </strong>Select <code>Web application</code> and hit <strong>Create.</strong></p>
<p>Give it a name and a redirect URL.</p>
<p>Enter the below URL in place of redirect URL. Here <code>php-google-signin</code> is the name of my project.</p>
<p><code>http://localhost/php-google-signin/index.php</code></p>
<p>All done. It will provide you with your <strong>client id</strong> and <strong>client secret key</strong>.</p>
<p>You are now done with the <strong>Google API Credentials </strong>part.</p>
<p>Let us now install <code>google-api-package</code> with the help of composer.</p>
<p>If you don't have composer installed in your machine, you can download it from here.</p>
<p><a target="_blank" href="https://getcomposer.org/">Composer</a></p>
<p>Once downloaded, install the required package by typing the following command from your terminal.</p>
<pre><code>composer <span class="hljs-keyword">require</span> google/apiclient:<span class="hljs-string">"^2.7"</span>
</code></pre><p>Once the package is installed inside your project folder, we can now move on with the <code>config.php</code> page. </p>
<p>Inside your <code>config.php</code> page, place the below code and you just need to replace two lines of code with your google's client id and client secret key.</p>
<pre><code><span class="hljs-meta">&lt;?php</span>  

<span class="hljs-comment">// include google client library for php autoload file</span>
<span class="hljs-keyword">require_once</span> <span class="hljs-string">'vendor/autoload.php'</span>;

<span class="hljs-comment">// make object of google API client</span>
$google_client = <span class="hljs-keyword">new</span> Google_Client();

<span class="hljs-comment">// set google oauth client ID</span>

<span class="hljs-comment">// enter your client id here inside the quotes</span>
$google_client-&gt;setClientId(<span class="hljs-string">'your-client-id-here-apps.googleusercontent.com'</span>);

<span class="hljs-comment">// set google OAuth client secret key</span>

<span class="hljs-comment">// enter your client secret key here inside the quotes</span>
$google_client-&gt;setClientSecret(<span class="hljs-string">'your-client-secret-key-here'</span>);

<span class="hljs-comment">// set google oauth redirect uri</span>
$google_client-&gt;setRedirectUri(<span class="hljs-string">'http://localhost/php-learning/index.php'</span>);

<span class="hljs-comment">// to get email and profile</span>
$google_client-&gt;addScope(<span class="hljs-string">'email'</span>);
$google_client-&gt;addScope(<span class="hljs-string">'profile'</span>);

<span class="hljs-comment">// start session on web page</span>
session_start();

<span class="hljs-meta">?&gt;</span>
</code></pre><p>On line number 12, enter you <code>client id</code> which you copied from google.</p>
<pre><code><span class="hljs-comment">// enter client id inside the quotes</span>
$google_client-&gt;setClientId(<span class="hljs-string">''</span>);
</code></pre><p>On line number 17, enter your <code>client secret</code>.</p>
<pre><code><span class="hljs-comment">// client secret key inside the quotes</span>
$google_client-&gt;setClientSecret(<span class="hljs-string">''</span>);
</code></pre><p>You are done with the <code>config.php</code> file and we can now move on to <code>index.php</code>.</p>
<p>Inside your <code>index.php</code> file, paste the following code.</p>
<pre><code><span class="php"><span class="hljs-meta">&lt;?php</span>  

<span class="hljs-keyword">include</span> <span class="hljs-string">'config.php'</span>;

$login_btn = <span class="hljs-string">''</span>;

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($_GET[<span class="hljs-string">'code'</span>])) {

    <span class="hljs-comment">// fetching the token</span>
    $token = $google_client-&gt;fetchAccessTokenWithAuthCode($_GET[<span class="hljs-string">'code'</span>]);

    <span class="hljs-comment">// check for any error while </span>
    <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">isset</span>($token[<span class="hljs-string">'error'</span>])) {

        <span class="hljs-comment">// set access token used for requests</span>
        $google_client-&gt;setAccessToken($token[<span class="hljs-string">'access_token'</span>]);


        <span class="hljs-comment">// store access token in session for future use</span>
        $_SESSION[<span class="hljs-string">'access_token'</span>] = $token[<span class="hljs-string">'access_token'</span>];

        <span class="hljs-comment">// create object of google service oauth2 class</span>
        $google_service = <span class="hljs-keyword">new</span> Google_Service_Oauth2($google_client);

        <span class="hljs-comment">// get user profile data from google</span>
        $data = $google_service-&gt;userinfo-&gt;get();

        <span class="hljs-comment">// find profile data and store it in session variable</span>
        <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">empty</span>($data[<span class="hljs-string">'given_name'</span>])) {
            $_SESSION[<span class="hljs-string">'fname'</span>] = $data[<span class="hljs-string">'given_name'</span>];
        }

        <span class="hljs-comment">// fetch the first name and store it in the session variable</span>
        <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">empty</span>($data[<span class="hljs-string">'family_name'</span>])) {
            $_SESSION[<span class="hljs-string">'lname'</span>] = $data[<span class="hljs-string">'family_name'</span>];
        }

        <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">empty</span>($data[<span class="hljs-string">'email'</span>])) {
            $_SESSION[<span class="hljs-string">'email'</span>] = $data[<span class="hljs-string">'email'</span>];
        }

        <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">empty</span>($data[<span class="hljs-string">'picture'</span>])) {
            $_SESSION[<span class="hljs-string">'picture'</span>] = $data[<span class="hljs-string">'picture'</span>];
        }

    }

}

<span class="hljs-comment">// check of the user is logged in using google account.</span>
<span class="hljs-keyword">if</span> (!<span class="hljs-keyword">isset</span>($_SESSION[<span class="hljs-string">'access_token'</span>])) {
    $login_btn = <span class="hljs-string">'&lt;a href="'</span>.$google_client-&gt;createAuthUrl().<span class="hljs-string">'"&gt;Login with Google&lt;/a&gt;'</span>;
}

<span class="hljs-meta">?&gt;</span></span><span class="xml">

<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Google Login<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

    </span><span class="php"><span class="hljs-meta">&lt;?php</span> <span class="hljs-keyword">if</span> ($login_btn == <span class="hljs-string">''</span>) {

        <span class="hljs-comment">// if login btn is a blank string, it means we have the auth token</span>

    <span class="hljs-meta">?&gt;</span></span><span class="xml">

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome to Google Profile<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Name: </span><span class="php"><span class="hljs-meta">&lt;?php</span> <span class="hljs-keyword">echo</span> $_SESSION[<span class="hljs-string">'fname'</span>]; <span class="hljs-meta">?&gt;</span></span><span class="xml"><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Email: </span><span class="php"><span class="hljs-meta">&lt;?php</span> <span class="hljs-keyword">echo</span> $_SESSION[<span class="hljs-string">'email'</span>]; <span class="hljs-meta">?&gt;</span></span><span class="xml"><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"</span></span></span><span class="php"><span class="hljs-meta">&lt;?php</span> <span class="hljs-keyword">echo</span> $_SESSION[<span class="hljs-string">'picture'</span>]; <span class="hljs-meta">?&gt;</span></span><span class="xml"><span class="hljs-tag"><span class="hljs-string">"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"logout.php"</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>


    </span><span class="php"><span class="hljs-meta">&lt;?php</span> } <span class="hljs-keyword">else</span> { <span class="hljs-meta">?&gt;</span></span><span class="xml">

        <span class="hljs-comment">&lt;!-- we don't have the auth token, we need to login the user --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            </span><span class="php"><span class="hljs-meta">&lt;?php</span> <span class="hljs-keyword">echo</span>($login_btn); <span class="hljs-meta">?&gt;</span></span><span class="xml">
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    </span><span class="php"><span class="hljs-meta">&lt;?php</span> } <span class="hljs-meta">?&gt;</span></span><span class="xml">

<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
</code></pre><p>I know this is not the best looking sign-in page but this post is not about CSS styling. If you want to style your index page, you can do by adding a stylesheet.</p>
<p>Now, we are done with the login part. If you want to test the link, open your browser and paste the link of your project <code>index.php</code> and it will ask you to <code>login with google</code>.</p>
<p>Use any of your Gmail and it will log you in and will show you your name, email and your profile picture.</p>
<p>Now we are left with the signout or the logout part. Below is the code for <code>logout.php</code></p>
<pre><code><span class="hljs-meta">&lt;?php</span>  

<span class="hljs-keyword">include</span> (<span class="hljs-string">'config.php'</span>);

$accesstoken = $_SESSION[<span class="hljs-string">'access_token'</span>];

<span class="hljs-comment">// reset oauth token</span>
$google_client-&gt;revokeToken($accesstoken);

<span class="hljs-comment">// destroy entire session data</span>
session_destroy();

<span class="hljs-comment">// redirect page to index.php</span>
header(<span class="hljs-string">'location:index.php'</span>);

<span class="hljs-meta">?&gt;</span>
</code></pre><p>You are done with the PHP Google Sign in part. I hope you liked my post on <strong> login with Google in a PHP web app </strong>and if you found my post helpful, please share it with your friends and if you have any doubt, feel free to comment below.</p>
<p>Thanks for your time and I'll meet you in my next post. Take care and happy coding🙂!</p>
]]></content:encoded></item><item><title><![CDATA[Understanding the basic concepts of CRUD in SQL]]></title><description><![CDATA[Hi, welcome back. In this post, we are going to understand the basic concepts of SQL query and why it is very crucial for developers.
Every developer at some point of time in his developer journey might have come across SQL.
But before getting starte...]]></description><link>https://blog.pratik.dev/crud-in-sql</link><guid isPermaLink="true">https://blog.pratik.dev/crud-in-sql</guid><category><![CDATA[SQL]]></category><category><![CDATA[MySQL]]></category><category><![CDATA[crud]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Sun, 11 Oct 2020 16:53:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607792031369/nJNRIPPwn.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hi, welcome back. In this post, we are going to understand the basic concepts of <strong>SQL</strong> query and why it is very crucial for developers.
Every developer at some point of time in his developer journey might have come across SQL.
But before getting started, I'd like to explain what is SQL.</p>
<h2 id="what-is-sql">What is SQL?</h2>
<p><strong>SQL</strong> is Structured Query Language, which is a computer language for storing, manipulating and retrieving data stored in a<strong> Relational Database</strong>.</p>
<p>It is the standard language for Relational Database System.</p>
<p>The term <code>CRUD</code> stands for <code>CREATE</code>, <code>READ</code>, <code>UPDATE</code> and <code>DELETE</code> or <code>DESTROY</code>.</p>
<p>Let's start with the <code>CREATE</code> statement in SQL.</p>
<p>One more thing. If you want to try these queries, you can try them online and you don't have to configure the database locally. Here is the link to an online database.</p>
<p><a target="_blank" href="https://sqliteonline.com/">SQL Online IDE - for Data Science</a></p>
<h3 id="create">CREATE</h3>
<p>The create statement can be used for both <strong>Database</strong> and <strong>Table</strong> creation. Let's see the database creation.</p>
<p><strong>Creating Database</strong></p>
<p>We'll start with the query for database creation.</p>
<pre><code><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">DATABASE</span> ecommerce;
</code></pre><p>This query will help you in creating a database named <strong>ecommerce</strong>.</p>
<p>Now, let's try to create a table with the <code>CREATE</code> statement.</p>
<p>If you don't know what a table is, read more about it here.
<a target="_blank" href="https://en.wikipedia.org/wiki/Table_(database">Table (database) - Wikipedia</a>)</p>
<p><strong>Creating Table</strong></p>
<p>For creating a table in the database, we need to pass column names with their data types in the query.</p>
<p>Here I'll be creating a <strong><code>users</code></strong> table.</p>
<pre><code><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> <span class="hljs-keyword">users</span> (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>, 
    <span class="hljs-keyword">name</span> <span class="hljs-keyword">STRING</span>,
    PRIMARY <span class="hljs-keyword">KEY</span> (<span class="hljs-keyword">id</span>)
);
</code></pre><p>The above query will create a table named <code>users</code> and, it will have columns named <strong><code>id</code></strong>, <strong><code>name</code></strong>.</p>
<blockquote>
<p>To identify every row uniquely, we have <code>id</code> and, we increment them automatically and we'll also set them as <code>PRIMARY KEY</code> and, it should be <code>NOT NULL</code>.</p>
</blockquote>
<h3 id="insert">INSERT</h3>
<p>Now we are done with the creating database and table we can now try to store some data in the users table.</p>
<p>To insert data in the table, we have the <code>INSERT</code> statement.</p>
<pre><code><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-keyword">users</span>
<span class="hljs-keyword">VALUES</span> (<span class="hljs-number">1</span>, <span class="hljs-string">"Pratik Sah"</span>);
</code></pre><p>It will add a new row in the users table and the values will be stored in the respective columns or fields.</p>
<p>Try inserting some rows on your own.</p>
<h3 id="read">READ</h3>
<p>We already have stored some useful data in the table, time to retrieve them.</p>
<p>For reading, we have the <strong><code>SELECT</code></strong> statement.</p>
<p>Suppose we want to access <code>name</code> column from the table, we'll write:</p>
<pre><code><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">name</span> <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span>;
</code></pre><p>If we want to select everything from the table, we use <code>*</code> for that.</p>
<pre><code><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span>;
</code></pre><p><strong><code>CONDITIONS</code></strong></p>
<p>Suppose we want to read only those data which satisfies a particular condition, then we'll use <code>WHERE</code> in our query.</p>
<pre><code><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span> <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">name</span> = <span class="hljs-string">"Pratik"</span>;
</code></pre><p>Here, we'll get those results only which have <code>name</code> equals to <code>Pratik</code> in the table <code>users</code>.</p>
<p>We can also use id for querying a particular row from the table. For example, <code>SELECT name FROM users WHERE id=1</code> and it will return us the name of the row where the id will be 1.</p>
<h3 id="update">UPDATE</h3>
<p>We now have our data stored in our table. We may want to change the name of the user or maybe the user wants to change the email. In that case, we can use the update statement.</p>
<pre><code><span class="hljs-keyword">UPDATE</span> <span class="hljs-keyword">users</span>
<span class="hljs-keyword">SET</span> <span class="hljs-keyword">name</span>=<span class="hljs-string">'Pratik'</span>
<span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span>=<span class="hljs-number">1</span>;
</code></pre><p>The above statement will help us to update the name of the user with id equals to 1. We can use this statement for making any changes stored in the table.</p>
<h3 id="delete">DELETE</h3>
<p>Sometimes what happens is, suppose a user wants to delete his account from our portal. We may want to delete his record from our users table and to that, we use the <code>DELETE</code> statement.</p>
<p>The delete statement helps us in deleting the data from our table. </p>
<pre><code><span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">FROM</span> <span class="hljs-keyword">users</span>
<span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span>=<span class="hljs-number">1</span>;
</code></pre><p>Now, this will delete the entire row from the users table where id will be 1.</p>
<p><strong>NOTE: </strong>Don't forget to use the <code>WHERE</code> or else it will delete the entire row from the table.</p>
<p>Sometimes we want to add a completely new column in our table. Now, in that case, we have to <code>ALTER</code> our table.</p>
<h3 id="alter">ALTER</h3>
<p><code>ALTER</code> is used to add, delete or modify columns in an existing table.</p>
<p>Suppose we want to add a new field in our users table where we want to store the age of user. We'll add a new column using the <code>ALTER</code> keyword.</p>
<pre><code><span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">TABLE</span> <span class="hljs-keyword">users</span>
<span class="hljs-keyword">ADD</span> age <span class="hljs-built_in">INT</span>;
</code></pre><p>Now, this command will add a new column named age with the data type <code>INT</code> in our <code>users</code> table.</p>
<p>Well, this was all for today's post and if you found it helpful, please leave a like, share this post with your friends &amp; comment below if you have any doubts.</p>
<p>Thanks for your time and I'll meet you in my next post. Take care and happy coding🙂!</p>
]]></content:encoded></item><item><title><![CDATA[Host your static sites for free on Github]]></title><description><![CDATA[You might have created a personal portfolio or a web app which you want to host online and might want to show off to your friends but never could because you don't have it online?
Well, all your worries now come to an end as we'll be learning how to ...]]></description><link>https://blog.pratik.dev/how-to-host-a-static-site-for-free</link><guid isPermaLink="true">https://blog.pratik.dev/how-to-host-a-static-site-for-free</guid><category><![CDATA[GitHub]]></category><category><![CDATA[static]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Tue, 22 Sep 2020 16:46:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607791639410/VTMI1J4iC.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You might have created a personal portfolio or a web app which you want to host online and might want to show off to your friends but never could because you don't have it online?</p>
<p>Well, all your worries now come to an end as we'll be learning how to host your static portfolio or any static website for free without spending a penny or by sharing your credit card details (in case of AWS).</p>
<p>All you need is to be familiar with the <strong>git command line </strong>and <strong>Github </strong>and you are good to go.</p>
<h2 id="github-pageshttpspagesgithubcom"><a target="_blank" href="https://pages.github.com/">Github Pages</a></h2>
<p>Github is home to over 100 million repositories and 40 million developers working together to host and review code, manage projects, and build software together.</p>
<p>It is a code hosting platform for version control and collaborations where developers can work together on projects from anywhere.</p>
<p>You can learn about Git commands from <a target="_blank" href="https://www.linkedin.com/posts/activity-6688107202227642368-H5S7/">Ananya's notes on Git from here.</a></p>
<p><strong>Now, let's start with the hosting part.</strong></p>
<ol>
<li>Let's create a new repo: go to <a target="_blank" href="https://github.com/new">github.com/new</a></li>
<li>For Repository Name, enter <strong><code>username.github.io</code></strong> where <strong>username</strong> is your actual username.</li>
<li>Make sure your repository is <strong>public</strong>.</li>
<li><strong>Do not</strong> check "Initialize this repository with a README", we don't need it now.</li>
<li>Click "<strong>Create repository</strong>".</li>
</ol>
<p>You can also learn about Creating repository from here
<a target="_blank" href="https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-new-repository">Creating a new repository - GitHub Docs</a></p>
<p>I assume you had created a new directory with an Html file, a CSS file and a JS file in it. Both CSS and JS are optional but you must have at least one index.html file in it.</p>
<p>If you don't have one, copy the below code and paste it in your <code>index.html</code> file inside a new directory.</p>
<pre><code><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Js Intro!<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hi, welcome to my site!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre><p>Now, open a terminal and navigate to the current directory where your index.html file is located.</p>
<p>Now we need to initialize a new Git repository in the current working directory.</p>
<pre><code>$ git init
<span class="hljs-comment"># This will initialize a new git repo in the current directory. </span>
</code></pre><p>Now, we need to add the files in our new local repository. This stages them for the first commit.</p>
<pre><code>$ git <span class="hljs-keyword">add</span> .
</code></pre><p>Now we need to commit the files that you've staged in your local repository.</p>
<pre><code>$ git <span class="hljs-keyword">commit</span> -m "First commit"
</code></pre><p>At the top of your GitHub repository's Quick Setup page, copy the <strong>remote repository URL</strong>. It will look something like this.</p>
<p><code>https://github.com/username/username.github.io.git</code></p>
<p>Now, in the Command prompt, add the URL which you copied, for the remote repository where your local repository will be pushed.</p>
<pre><code>$ git remote add origin remote_repository_URL
<span class="hljs-comment"># remote_url: https://github.com/username/username.github.io.git</span>
<span class="hljs-comment"># please check for the username in the URL before proceding</span>
</code></pre><p>This will set the new remote URL for your local repository.</p>
<p>Now, we are ready to push our code to Github.</p>
<pre><code>$ git <span class="hljs-keyword">push</span> origin master
</code></pre><p>It might take up to 5-10 minutes and after that, you’ll be able to see your newly created page at <code>http://username.github.io/</code></p>
<p>If you make updates, be sure to push to the <strong>master</strong> branch!</p>
<p>If you want to link a custom domain name, here is a link to an in-depth guide on linking a custom domain name with Github.</p>
<p><a target="_blank" href="https://medium.com/@hossainkhan/using-custom-domain-for-github-pages-86b303d3918a">Using a custom domain for GitHub pages</a></p>
<p>Well, this was all for today's post and if you found it helpful, please leave a like &amp; comment below if you have any doubts.</p>
<p>Thanks for your time and I'll meet you in my next post. Take care and happy coding🙂!</p>
]]></content:encoded></item><item><title><![CDATA[Create a Todo app with jQuery and localStorage]]></title><description><![CDATA[Welcome back, in this post, we are going to create a todo app with jQuery and localStorage of the browser. 
To check the live app that I've created, here is the link to the app. It is a Progressive Web App so you can also install it on your device an...]]></description><link>https://blog.pratik.dev/create-a-todo-app-with-jquery-and-localstorage</link><guid isPermaLink="true">https://blog.pratik.dev/create-a-todo-app-with-jquery-and-localstorage</guid><category><![CDATA[jQuery]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Wed, 16 Sep 2020 16:41:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607791324318/JOSQeEP9y.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome back, in this post, we are going to create a <strong>todo</strong> app with jQuery and localStorage of the browser. </p>
<p>To check the live app that I've created, <a target="_blank" href="https://jqtodo.netlify.app">here is the link to the app</a>. It is a <strong>Progressive Web App</strong> so you can also install it on your device and use it as a native app.</p>
<p>All of our todo items will be stored in the local storage of our browser and we'll load the todos from the browser every time we'll load our app. </p>
<p>This will eliminate the use of a database for storing our todos and you can read more about local storage here.</p>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">Window.localStorage</a></p>
<p>Now, let's create the basic HTML structure of our todo app.</p>
<p>Create an <code>index.html</code> file in the root directory of your project. Here is the HTML code for our todo app.</p>
<pre><code><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>/&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Todo by Pratik<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"description"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"Offline Todo app, use on the go. No need of internet connectivity. Todo by Pratik is the best todo app you'll need."</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"shortcut icon"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"./img/todo.png"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"image/x-icon"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"manifest"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"./manifest.json"</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"main"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Todo by <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://pratiksah.com"</span>&gt;</span>Pratik<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Type and press Enter <span class="hljs-symbol">&amp;#8594;</span>"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"todo"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-info"</span>&gt;</span>Tap on todo to remove them.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- incomplete todo --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"incomplete"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- link to jq and external js --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>
      <span class="hljs-attr">src</span>=<span class="hljs-string">"https://code.jquery.com/jquery-3.5.1.slim.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./app.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre><p>Here, I've used jQuery and an external js file for handling all the logic for our app.</p>
<p>Now, to style our app, we are using some custom CSS.</p>
<p>Create a new <code>style.css</code> file in the root directory and paste the below code.</p>
<pre><code>* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">80px</span> <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.main</span> {
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">"Segoe UI"</span>, Roboto, Oxygen,
    Ubuntu, Cantarell, <span class="hljs-string">"Open Sans"</span>, <span class="hljs-string">"Helvetica Neue"</span>, sans-serif;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40vw</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> auto;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">58</span>, <span class="hljs-number">58</span>, <span class="hljs-number">58</span>);
}

<span class="hljs-selector-tag">a</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">100</span>, <span class="hljs-number">100</span>, <span class="hljs-number">100</span>);
  <span class="hljs-attribute">text-decoration</span>: none;
}

<span class="hljs-selector-tag">input</span> {
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">30px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">15px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">22px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">4px</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid <span class="hljs-built_in">rgb</span>(<span class="hljs-number">58</span>, <span class="hljs-number">58</span>, <span class="hljs-number">58</span>);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">58</span>, <span class="hljs-number">58</span>, <span class="hljs-number">58</span>);
}

<span class="hljs-selector-class">.text-info</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0px</span> <span class="hljs-number">0px</span> <span class="hljs-number">10px</span> <span class="hljs-number">0px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">117</span>, <span class="hljs-number">117</span>, <span class="hljs-number">117</span>);
  <span class="hljs-attribute">font-family</span>: -apple-system, BlinkMacSystemFont, <span class="hljs-string">'Segoe UI'</span>, Roboto, Oxygen, Ubuntu, Cantarell, <span class="hljs-string">'Open Sans'</span>, <span class="hljs-string">'Helvetica Neue'</span>, sans-serif;
}

<span class="hljs-selector-class">.card</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">15px</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">58</span>, <span class="hljs-number">58</span>, <span class="hljs-number">58</span>);
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">4px</span>;
  <span class="hljs-attribute">align-items</span>: center;
}
<span class="hljs-selector-class">.card</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">121</span>, <span class="hljs-number">119</span>, <span class="hljs-number">119</span>);
  <span class="hljs-attribute">cursor</span>: pointer;
}

<span class="hljs-selector-pseudo">::-webkit-scrollbar</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">10px</span>;
}

<span class="hljs-selector-pseudo">::-webkit-scrollbar-thumb</span> {
  <span class="hljs-attribute">background</span>:  <span class="hljs-built_in">rgb</span>(<span class="hljs-number">92</span>, <span class="hljs-number">91</span>, <span class="hljs-number">91</span>);
}


<span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">768px</span>) {
  <span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  }
  <span class="hljs-selector-class">.main</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">80vw</span>;
    <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">30px</span>;
  }
}
</code></pre><p>Now, this code will help you in styling your app and it will also make your app responsive as I've also used <code>media query</code>.</p>
<p>Let's create our <code>app.js</code> file inside the root directory and we'll write all of our logic in jQuery here.</p>
<p>We'll start by checking the data from the localStorage of the browser whenever our app will load.</p>
<p>To store any data in the localStorage, we use <code>localStorage.setItem('name', 'Pratik');</code></p>
<p>This will create a key named <code>name</code> and the value of this key will be <code>Pratik</code>.</p>
<p>Now, to get the data, we can use <code>localStorage.getItem('name')</code> and this will return us with the value stored in that key-value pair.</p>
<p>If no key is available with that name, this will return us <code>null</code>.</p>
<p>Now, we'll use the same logic to check for our previous todos stored in the localStorage and if exists, we'll fetch the data from the <code>localStorage</code> and load it in the <code>div</code> with class <code>card</code>.</p>
<pre><code>checkTodos();

<span class="hljs-comment">// check for data in localStorage</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkTodos</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// todos in the key of my localStorage</span>
  <span class="hljs-keyword">let</span> dataInLocalStorage = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"todos"</span>);
  <span class="hljs-comment">// check if it is null or not</span>
  <span class="hljs-keyword">if</span> (dataInLocalStorage == <span class="hljs-literal">null</span>) {
    todos = [];
  } <span class="hljs-keyword">else</span> {
    todos = <span class="hljs-built_in">JSON</span>.parse(dataInLocalStorage);
  }
  <span class="hljs-keyword">let</span> html = <span class="hljs-string">""</span>;
  todos.forEach(<span class="hljs-function">(<span class="hljs-params">todo, index</span>) =&gt;</span> {
    html += <span class="hljs-string">`&lt;div class='card' onclick='removeTodo(<span class="hljs-subst">${index}</span>);'&gt;<span class="hljs-subst">${todo}</span>&lt;/div&gt;`</span>;
  });
  $(<span class="hljs-string">".incomplete"</span>).empty().append(html);
}
</code></pre><p>Next, we'll write the logic to add todos and save them in the <code>localStorage</code>. </p>
<pre><code><span class="hljs-comment">// adding items in todos</span>

$(<span class="hljs-string">"input"</span>).on(<span class="hljs-string">"keypress"</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (e.which === <span class="hljs-number">13</span> &amp;&amp; $(<span class="hljs-string">"input"</span>).val() !== <span class="hljs-string">""</span>) {
    todo = $(<span class="hljs-string">"input"</span>).val();
    <span class="hljs-keyword">let</span> todosData = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"todos"</span>);
    <span class="hljs-keyword">if</span> (todosData == <span class="hljs-literal">null</span>) {
      todos = [];
    } <span class="hljs-keyword">else</span> {
      todos = <span class="hljs-built_in">JSON</span>.parse(todosData);
    }
    todos.push(todo);
    <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"todos"</span>, <span class="hljs-built_in">JSON</span>.stringify(todos));
    $(<span class="hljs-string">"input"</span>).val(<span class="hljs-string">""</span>);
    checkTodos();
  }
});
</code></pre><p>Here, you can see that I've also called the <code>checkTodos()</code> function to update the UI once a new todo is added.</p>
<p>Now, the final code to remove the todo from the localStorage and from the UI.</p>
<pre><code><span class="hljs-comment">// logic for removing todo from the todos list</span>

<span class="hljs-keyword">let</span> removeTodo = <span class="hljs-function">(<span class="hljs-params">index</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> todosData = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"todos"</span>);
  todos = <span class="hljs-built_in">JSON</span>.parse(todosData);
  todos.splice(index, <span class="hljs-number">1</span>);
  <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"todos"</span>, <span class="hljs-built_in">JSON</span>.stringify(todos));
  checkTodos();
};
</code></pre><p>Here, I've created an arrow function for removing the items from the todo. This will also remove the item from the <code>localStorage</code> and it will then update the localStorage with the new data.</p>
<p>The <code>removeTodo()</code> function will be called whenever we'll tap on any of our todo items.</p>
<p>Now, here is the complete code of <code>app.js</code> of the todo app.</p>
<pre><code>checkTodos();

<span class="hljs-comment">// check for data in localStorage</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkTodos</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// todos in the key of my localStorage</span>
  <span class="hljs-keyword">let</span> dataInLocalStorage = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"todos"</span>);
  <span class="hljs-comment">// check if it is null or not</span>
  <span class="hljs-keyword">if</span> (dataInLocalStorage == <span class="hljs-literal">null</span>) {
    todos = [];
  } <span class="hljs-keyword">else</span> {
    todos = <span class="hljs-built_in">JSON</span>.parse(dataInLocalStorage);
  }
  <span class="hljs-keyword">let</span> html = <span class="hljs-string">""</span>;
  todos.forEach(<span class="hljs-function">(<span class="hljs-params">todo, index</span>) =&gt;</span> {
    html += <span class="hljs-string">`&lt;div class='card' onclick='removeTodo(<span class="hljs-subst">${index}</span>);'&gt;<span class="hljs-subst">${todo}</span>&lt;/div&gt;`</span>;
  });
  $(<span class="hljs-string">".incomplete"</span>).empty().append(html);
}

<span class="hljs-comment">// adding items in todos</span>

$(<span class="hljs-string">"input"</span>).on(<span class="hljs-string">"keypress"</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (e.which === <span class="hljs-number">13</span> &amp;&amp; $(<span class="hljs-string">"input"</span>).val() !== <span class="hljs-string">""</span>) {
    todo = $(<span class="hljs-string">"input"</span>).val();
    <span class="hljs-keyword">let</span> todosData = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"todos"</span>);
    <span class="hljs-keyword">if</span> (todosData == <span class="hljs-literal">null</span>) {
      todos = [];
    } <span class="hljs-keyword">else</span> {
      todos = <span class="hljs-built_in">JSON</span>.parse(todosData);
    }
    todos.push(todo);
    <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"todos"</span>, <span class="hljs-built_in">JSON</span>.stringify(todos));
    $(<span class="hljs-string">"input"</span>).val(<span class="hljs-string">""</span>);
    checkTodos();
  }
});

<span class="hljs-comment">// logic for removing from the todos list</span>
<span class="hljs-keyword">let</span> removeTodo = <span class="hljs-function">(<span class="hljs-params">index</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> todosData = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"todos"</span>);
  todos = <span class="hljs-built_in">JSON</span>.parse(todosData);
  todos.splice(index, <span class="hljs-number">1</span>);
  <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"todos"</span>, <span class="hljs-built_in">JSON</span>.stringify(todos));
  checkTodos();
};
</code></pre><p>Now, you are done with the coding part and you can now start using it. </p>
<p>Well, this was all for today's post and if you found it helpful, please leave a like &amp; comment below and in my next post, we'll see how you can deploy your static web app for free on Netlify. </p>
<p>I'll be deploying this todo app on netlify and you can also add a domain name there for free.</p>
<p>Thanks for your time and I'll meet you in my next post. Take care and happy coding🙂!</p>
]]></content:encoded></item><item><title><![CDATA[Creating a weather app in Express Js using OpenWeatherMap API]]></title><description><![CDATA[Welcome back! In this post, we are going to make a weather app using Express JS, that will fetch weather data of a particular location with the help of OpenWeatherMap API. 
The API is free to use and you can get your API keys from the link below. Jus...]]></description><link>https://blog.pratik.dev/creating-a-weather-app-in-node-js-express-js-using-openweather-api</link><guid isPermaLink="true">https://blog.pratik.dev/creating-a-weather-app-in-node-js-express-js-using-openweather-api</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Express]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Thu, 10 Sep 2020 16:35:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607790959967/Tg5bU0bQl.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome back! In this post, we are going to make a weather app using Express JS, that will fetch weather data of a particular location with the help of <strong>OpenWeatherMap</strong> API. </p>
<p>The API is <strong>free</strong> to use and you can get your API keys from the link below. Just signup and you are good to go.</p>
<p><a target="_blank" href="https://openweathermap.org">Сurrent weather and forecast - OpenWeatherMap</a></p>
<p>Now we can copy the API key that we need to fetch the weather of a new location. Go to the API section and select the <strong>Current Weather Data </strong>and click <strong>Subscribe</strong>.</p>
<p>Now click on get API key under the free plan and copy the key which they provided.</p>
<p>Once you are done with the account creation and copying the key, we can now start with the code.</p>
<p>Open your terminal and navigate to the location where you want to create your Node Js app.</p>
<p>Next, we need to create a new directory and name it <strong>weatherapp </strong>or you can name it as per your choice.</p>
<p><code>mkdir weatherapp</code></p>
<p>Navigate to this directory.</p>
<p><code>cd weatherapp</code></p>
<p>Now, we need to set up a node js project in this directory. Write the following command in your terminal and follow the instructions as shown there.</p>
<p><code>npm init</code></p>
<p>Open your weatherapp directory in you favourite text editor and we can now move on to the code.</p>
<p>Create a new file inside your weatherapp directory and name it <code>app.js</code>.</p>
<p>This is going to be the starting file of our app. We'll come back to this file once we are done with the installation of the requires packages.</p>
<p>Now, we'll install all the required packages for this project.</p>
<p>The first thing we need is to install is Express and body-parser.</p>
<p>Run the following command in your terminal inside your project's directory.</p>
<p><code>npm install express --save</code></p>
<p><code>npm install body-parser</code></p>
<p>For templates, we are going to use EJS. You can read more about ejs on their official docs from the link below.</p>
<p><a target="_blank" href="https://ejs.co">EJS -- Embedded JavaScript templates</a></p>
<p>We'll first start with the installation of ejs in our project with the help of the following command.</p>
<p><code>npm install ejs</code></p>
<p>Next, we need to create a new directory named <code>views</code> in our root directory.</p>
<p>Inside the views directory, we are going to store all of our templates.</p>
<p>Now create a new file inside views directory and name it <code>index.ejs</code>.</p>
<p>Copy the following code and paste it in your <code>index.ejs</code> file.</p>
<pre><code><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Weatherly<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"</span>
      <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%</span> <span class="hljs-attr">if</span> (<span class="hljs-attr">data</span> === <span class="hljs-string">''</span>) { %&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container mt-5 col-lg-6"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"display-4 text-center"</span>&gt;</span>Weatherly🌤! by <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://pratiksah.com"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>Pratik<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card-body"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h5</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card-title"</span>&gt;</span>Search weather of your location<span class="hljs-tag">&lt;/<span class="hljs-name">h5</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"location"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Location"</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"display-5 mt-3 text-muted"</span>&gt;</span>Default location is Purnia, In<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-primary"</span>&gt;</span>Go<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%</span> } <span class="hljs-attr">else</span> <span class="hljs-attr">if</span> (<span class="hljs-attr">data</span> === <span class="hljs-string">'0'</span>) { %&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container mt-5"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card-body"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card-title"</span>&gt;</span>Oops! Lost in space🚀, try locations from Earth🌏 !<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-center"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-primary mt-5 mx-auto"</span>&gt;</span>New location<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%</span> } <span class="hljs-attr">else</span> { %&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container mt-5"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"display-4 text-center"</span>&gt;</span>Weatherly! by <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://pratiksah.com"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>Pratik<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card-body"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h5</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card-title"</span>&gt;</span>Weather in <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">data.name</span> %&gt;</span>, <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">data.sys.country</span> %&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h5</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-muted"</span>&gt;</span>Lat: <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">data.coord.lat</span> %&gt;</span>, Lon: <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">data.coord.lon</span> %&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"float-right"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"http://openweathermap.org/img/wn/&lt;%= data.weather[0].icon %&gt;@2x.png"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"icon"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"display-1"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">data.main.temp</span>%&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">sup</span>&gt;</span>o<span class="hljs-tag">&lt;/<span class="hljs-name">sup</span>&gt;</span>C<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-muted"</span>&gt;</span>Feels like <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">data.main.feels_like</span> %&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">sup</span>&gt;</span>o<span class="hljs-tag">&lt;/<span class="hljs-name">sup</span>&gt;</span>C<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h5</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-capitalize font-weight-bold"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">data.weather</span>[<span class="hljs-attr">0</span>]<span class="hljs-attr">.description</span> %&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h5</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"overflow-x"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pr-5 inf"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fas fa-wind"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span> Wind <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">data.wind.speed</span> %&gt;</span> m/sec<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pr-5 inf"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fas fa-paper-plane"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span> Pressure <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">data.main.pressure</span> %&gt;</span> mb<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pr-5 inf"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fas fa-tint"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span> Humidity <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">data.main.humidity</span> %&gt;</span>%<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pr-5 inf"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fas fa-eye"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span> Visibility <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">data.visibility</span>/<span class="hljs-attr">1000</span> %&gt;</span> km<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pr-5 inf"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fas fa-cloud"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span> Cloudiness <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> <span class="hljs-attr">data.clouds.all</span> %&gt;</span>%<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-center"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-primary mt-5 mx-auto"</span>&gt;</span>New location<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%</span> } %&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://kit.fontawesome.com/ad862d8e11.js"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre><p>Now, come back to our app.js file and import express, https and body-parser.</p>
<pre><code><span class="hljs-keyword">const</span> express = <span class="hljs-keyword">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> https = <span class="hljs-keyword">require</span>(<span class="hljs-string">'https'</span>)
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-keyword">require</span>(<span class="hljs-string">'body-parser'</span>)
</code></pre><p>Now, we'll create a new express app.
<code>const app = express()</code></p>
<p>Now, we'll set up our view-engine to ejs.
<code>app.set('view engine', 'ejs')</code></p>
<p>Now we'll create a middleware that will help us in parsing the content of the form submitted.</p>
<pre><code><span class="hljs-selector-tag">app</span><span class="hljs-selector-class">.use</span>(<span class="hljs-selector-tag">bodyParser</span><span class="hljs-selector-class">.urlencoded</span>({<span class="hljs-attribute">extended</span>: true}))
</code></pre><p>Next, we will be serving a form with an input field that will take location as an input.</p>
<p>The above <code>ejs</code> file will help us to serve a form that will take input of a location from the user.</p>
<p>Here I have used an external CSS, if you want to use that, here is the code to it. </p>
<pre><code><span class="hljs-selector-class">.fas</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">1.3em</span> <span class="hljs-meta">!important</span>;
}

<span class="hljs-keyword">@media</span> <span class="hljs-keyword">only</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">800px</span>) {
  <span class="hljs-selector-class">.inf</span> {
    <span class="hljs-attribute">display</span>: block <span class="hljs-meta">!important</span>;
  }
  <span class="hljs-selector-class">.display-1</span> {
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">3rem</span>;
  }
}
</code></pre><p>style.css
This <strong>CSS</strong> file is to be placed inside a <code>public</code> directory inside the root directory and if you don't know how to serve a static file in node js using express, you can follow my other post, here is the link to it.</p>
<p><a target="_blank" href="/serving-static-files-in-node-js/">Serving static files in Node js</a></p>
<p>Now, let's write our complete code for <code>index.js</code> file. Here is the code for the api call.</p>
<pre><code><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'https'</span>)
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'body-parser'</span>)


<span class="hljs-keyword">const</span> app = express()

<span class="hljs-comment">// telling my app to use ejs as the default template engine</span>
app.set(<span class="hljs-string">'view engine'</span>, <span class="hljs-string">'ejs'</span>)

app.use(bodyParser.urlencoded({
  <span class="hljs-attr">extended</span>: <span class="hljs-literal">true</span>
}))

<span class="hljs-comment">// code to serve the static files</span>
app.use(express.static(<span class="hljs-string">"public"</span>))

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.render(<span class="hljs-string">'index'</span>, {<span class="hljs-attr">data</span>: <span class="hljs-string">''</span>});
})

app.post(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> location = req.body.location ? req.body.location : <span class="hljs-string">"Purnia"</span>;
  <span class="hljs-keyword">const</span> appId = <span class="hljs-string">"Your_API_Key_Here"</span>;
  <span class="hljs-keyword">const</span> url = <span class="hljs-string">"https://api.openweathermap.org/data/2.5/weather?q="</span> + location + <span class="hljs-string">"&amp;appid="</span> + appId + <span class="hljs-string">"&amp;units=metric"</span>;
  https.get(url, <span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (response.statusCode === <span class="hljs-number">200</span>) {
      response.on(<span class="hljs-string">"data"</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        <span class="hljs-keyword">const</span> weatherData = <span class="hljs-built_in">JSON</span>.parse(data);
        res.render(<span class="hljs-string">'index'</span>, {<span class="hljs-attr">data</span>: weatherData});
      })
    } <span class="hljs-keyword">else</span> {
      res.render(<span class="hljs-string">'index'</span>, {<span class="hljs-attr">data</span>: <span class="hljs-string">"0"</span>})
    }
  })
})

app.listen(process.env.PORT || <span class="hljs-number">80</span>)
</code></pre><p>Once you are done with the final code of <code>app.js</code> you can now start your server and it will launch your app.</p>
<p>To start your server, type <code>npm start</code> and this will run ther server on port <code>80</code>.</p>
<p>Now, open your browser and go to <code>http://localhost/</code>, you'll see your app running. Enter any location and it will show you the weather of that location.</p>
<p><a target="_blank" href="https://intense-spire-12796.herokuapp.com/">Here is the link</a> to the app which I made using OpenWeatherMap and hosted on Heroku for free.</p>
<p>Well, this was all for today's post and if you found it helpful, please leave a like &amp; comment and in my next post, I'll teach you how you can create your own todo app with jQuery and localStorage.</p>
<p>Thanks for your time and I'll meet you in my next post. Take care and happy coding🙂!</p>
]]></content:encoded></item><item><title><![CDATA[Serving static files in Node js]]></title><description><![CDATA[In this post, we will learn serving static files in Node Js using Express Js. Static files are like images, CSS, js etc. The static js file is completely different from the js we are using in Node Js.
Serving static files using Express Js
Express Js ...]]></description><link>https://blog.pratik.dev/serving-static-files-in-node-js</link><guid isPermaLink="true">https://blog.pratik.dev/serving-static-files-in-node-js</guid><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Sat, 29 Aug 2020 16:30:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607790739789/NBuBVOPgb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this post, we will learn serving static files in Node Js using Express Js. Static files are like images, CSS, js etc. The static js file is completely different from the js we are using in Node Js.</p>
<h2 id="serving-static-files-using-express-js">Serving static files using Express Js</h2>
<p>Express Js has a built-in middleware <strong><code>express.static</code></strong> that helps us to serve the static files in Node Js application.</p>
<p>You can learn more about <code>express.static</code> from their official docs.</p>
<p><a target="_blank" href="https://expressjs.com/en/starter/static-files.html">Serving static files in Express</a></p>
<p>While using <code>express.static</code>, we can provide the directory name to the method where the static files are stored.</p>
<p>Let's create a directory where we want to store our static files and name it <strong>public</strong>. Open a terminal and run the below command.</p>
<p><code>mkdir public &amp;&amp; cd public</code></p>
<p>Now, we can paste any static file here like images or <code>CSS/JS</code> files. </p>
<p>Here I'll be creating a <strong><code>styles.css</code></strong> file.</p>
<p>I'll be using this static file for styling my Html page.</p>
<p><code>touch styles.css</code></p>
<p>This will create a new file named <strong><code>styles.css</code></strong>.</p>
<p>Below is the sample code for CSS. Copy the code and paste it in your styles.css file.</p>
<pre><code>* {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
}

<span class="hljs-selector-tag">a</span> {
  <span class="hljs-attribute">text-decoration</span>: none;
}

<span class="hljs-comment">/* your custom css here */</span>
</code></pre><p>Now we have our static file in our public directory, its time to serve it using Express Js.</p>
<p>Add the following code to your main js file after creating the express app.</p>
<pre><code><span class="hljs-keyword">const</span> express = <span class="hljs-keyword">require</span>(<span class="hljs-string">'express'</span>)

<span class="hljs-keyword">const</span> app = express()

<span class="hljs-comment">// this middleware will help you to serve your static files</span>
app.<span class="hljs-keyword">use</span>(express.<span class="hljs-built_in">static</span>(<span class="hljs-string">'public'</span>))

app.listen(<span class="hljs-number">80</span>)
</code></pre><p>Now, this middleware will help us to access all the static files that are in the <strong>public</strong> directory.</p>
<p>Let's create a <strong>views </strong>directory in our root directory and inside it, we can create <code>index.html</code> file.</p>
<p>This file will be served to the users whenever someone comes to the root URL.</p>
<p>Below is the sample code for <code>index.html</code> file. Copy the code and paste it in your <code>index.html</code> file.</p>
<pre><code><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Index JS<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Home Page<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/product"</span>&gt;</span>Products<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre><p>Now, we have our Html code and our CSS static file, let us try to link our CSS with our Html file.</p>
<p><code>&lt;link rel="stylesheet" href="/styles.css"&gt;</code></p>
<p>The above line will try to locate the CSS file in the same directory if it was a static website, but because of <code>express.static</code> middleware code, <strong>Express</strong> will provide the path of our <strong>public</strong> directory and this will help the Html code to access the CSS file.</p>
<p>Well, this was all for today. I know this post was a bit small but this will help you to serve your static files in Node Js.</p>
<p>Thanks for your time. If you found this post helpful😊, please share this with your friends.</p>
<p>If you stuck into some kind of problem, feel free to comment below. I'll be happy to help you🙂.</p>
<p>Till then bye and happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Create a contact form with Django and SQLite]]></title><description><![CDATA[Welcome back. In this post, we'll be using HTML template and Django to create a contact form with Django and SQLite. We will also try to see all the listings in the admin panel.
This is a basic Django web application focusing on some basic crud and w...]]></description><link>https://blog.pratik.dev/contact-form-with-django</link><guid isPermaLink="true">https://blog.pratik.dev/contact-form-with-django</guid><category><![CDATA[Django]]></category><category><![CDATA[SQLite]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Fri, 21 Aug 2020 16:25:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607319673291/OgJDRQiN3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome back. In this post, we'll be using <strong>HTML</strong> template and <strong>Django </strong>to create a contact form with Django and SQLite. We will also try to see all the listings in the admin panel.</p>
<p>This is a basic Django web application focusing on some basic crud and we will be saving the data in an SQLite database.</p>
<h2 id="why-django">Why Django?</h2>
<blockquote>
<p>Django is a free and open-source python-based web framework for creating dynamic web apps. Some popular sites that use Django are Instagram, Mozilla, The Washington Post, etc.</p>
</blockquote>
<p><a target="_blank" href="https://www.djangoproject.com/">The Web framework for perfectionists with deadlines | Django!</a></p>
<p>We will use bootstrap for styling the form. For using the bootstrap, we can use either <strong>CDN </strong> or we can download the CSS files from the bootstrap site.</p>
<p>Below is the code for a simple Form made using bootstrap.</p>
<pre><code><span class="hljs-meta">&lt;!doctype <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-comment">&lt;!-- Required meta tags --&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1, shrink-to-fit=no"</span>&gt;</span>

  <span class="hljs-comment">&lt;!-- Bootstrap CSS --&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"</span>
    <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Contact<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-center my-5"</span>&gt;</span>Contact Form<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"row justify-content-center"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col-lg-6"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">""</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"name"</span>&gt;</span>Full Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Your Name"</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"email"</span>&gt;</span>Email address<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"name@example.com"</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"message"</span>&gt;</span>Your message<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">textarea</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"desc"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"message"</span> <span class="hljs-attr">rows</span>=<span class="hljs-string">"3"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">textarea</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-primary"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre><p>Here we have used the CDN link for including bootstrap in our HTML code.</p>
<p>To submit our form, I have used <em>input type submit</em> but you can also use the button tag in place of input type submit.</p>
<p>In place of form action, we will try to submit the form in the same path that will be the root URL and we will handle form submission in our code.</p>
<p>This code will help us in creating a form which we will be using it in the templates of our <strong>Django</strong> project.</p>
<p>Now we are done with the HTML, and now, we can start with the Django project setup.</p>
<p><strong>Note</strong>: <em>Before starting with Django, we will create a virtual environment where we will have all our files and packages stored.</em></p>
<h2 id="creating-a-virtual-environment">Creating a Virtual Environment</h2>
<p>Before starting with creating a virtual environment, we need to install a package that will help us in creating the environment.</p>
<blockquote>
<p>A virtual environment is a tool to create a private workspace for a Python application.</p>
</blockquote>
<p>One of the major advantages of using a virtual environment is the ability to install modules locally.</p>
<p>You can also export a working environment and execute Python programs in that environment.</p>
<p>Make sure you have the latest version of Python installed on your system.</p>
<p>Now you are done with that, and we can now move to the next step of creating the virtual environment.</p>
<p>We have many python packages for creating the virtual environment. Here I'll be using the <strong><code>pipenv</code></strong>.</p>
<p>The main reason for using <strong><code>pipenv</code></strong> is that its commands are the same on all the platforms.</p>
<p>To install this package on your system, copy the below command and paste it in your terminal.</p>
<pre><code><span class="hljs-comment"># for mac and Linux users</span>
pip3 <span class="hljs-keyword">install</span> pipenv

<span class="hljs-comment"># for windows users</span>
pip <span class="hljs-keyword">install</span> pipenv
</code></pre><p>terminal
This package automatically creates and manages virtual env for your projects, as well as adds/remove packages from your pipfile as you install/remove packages.</p>
<p>Now this package is installed on your system. The next step is to create a new virtual environment.</p>
<p>For creating a new virtual environment, let's first create a new directory which we are going to use it as our virtual environment for this project, and name it <strong><code>myenv</code></strong> for now. </p>
<p>You can name it anything you want but for now, keep it the same.</p>
<pre><code># command <span class="hljs-keyword">to</span> <span class="hljs-keyword">create</span> a <span class="hljs-built_in">new</span> directory
mkdir myenv

# command <span class="hljs-keyword">to</span> <span class="hljs-keyword">open</span> that directory
cd myenv
</code></pre><p>terminal
<code>mkdir myenv</code> will help you in creating a new directory, and <code>cd myenv</code> will help you to change the working directory to <code>myenv</code>. </p>
<p>Now we are inside our folder where we want to create the env, run the following command to create a new environment inside <strong><code>myenv</code></strong>directory.</p>
<pre><code># command <span class="hljs-keyword">to</span> <span class="hljs-keyword">create</span> a <span class="hljs-built_in">new</span> virtual env
pipenv shell
</code></pre><p>terminal
This command will <strong>create </strong>and <strong>activate </strong>a new virtual environment in your present directory, and now you are ready to install new packages in your env.</p>
<p>But wait. You can't install any packages simply by writing <strong><code>pip install</code></strong>.</p>
<p>Since you are inside the virtual env of <code>pipenv</code>, you need to use a slightly modified command to install any packages.</p>
<p>Now don't get panic here. The command is not so hard to keep it in mind.</p>
<p>Earlier we used to write <strong><code>pip install xyz-package</code>, </strong>but now we need to write <strong><code>pipenv install xyz-package</code></strong>.</p>
<p>Not so major change but worth keeping in mind.</p>
<p>Now we are ready with the package installation, and we can head over to install <strong>Django.</strong></p>
<p>Head over to the official documentation of Django by clicking <a target="_blank" href="https://docs.djangoproject.com/en/3.1/">here</a>.</p>
<p>Copy the following command and paste it into your terminal, and it will help you to install Django.</p>
<pre><code><span class="hljs-comment"># this will install Django in your virtual env</span>
<span class="hljs-attribute">pipenv</span> install Django
</code></pre><p>terminal
To check the installed packages, type the following command, and it will list all the installed packages in your terminal.</p>
<pre><code>pip <span class="hljs-keyword">freeze</span>
</code></pre><p>terminal
You'll see the list of all the installed packages in your terminal, and it will also have Django in it.</p>
<p><strong>Note: </strong>The Django which we tried to install is installed only in this virtual env and not globally. So you cannot use it from anywhere. </p>
<p>This also means if you need to create a new Django project, you need to create a new virtual env and install Django from fresh again.</p>
<h2 id="creating-a-django-project">Creating a Django project</h2>
<p>Now we are installed with Django, and we can move on to creating a new project with Django.</p>
<p>To create a new Django project, copy the following command and paste it in your terminal.</p>
<pre><code>django-<span class="hljs-keyword">admin</span> startproject contactform
</code></pre><p>terminal
Here the <strong><code>contactform</code></strong>is the name of our project.</p>
<p>You can now see that <code>django-admin</code> has created some files for us to work on. We are not going to change anything as of now.</p>
<p>Next is to change the directory to <code>contactform</code> and start our server.</p>
<pre><code><span class="hljs-comment"># to change the working directory</span>
<span class="hljs-built_in">cd</span> contactform

<span class="hljs-comment"># to see the files and folders</span>
ls
</code></pre><p>terminal
Here you can see the folders and files of our <code>contactform</code>.</p>
<p><code>ls</code> helps us to list all the files and folders inside our current directory. Inside this directory, we have a <code>manage.py</code> file, a <code>db.sqlite3</code> and a directory name <code>contactform</code>.</p>
<p><code>db.sqlite3</code> is optional. It may get created or maybe not, but don't worry. We will seel it later.</p>
<p>Now we have our project created, and we can start our server now and have a look at it in our browser.</p>
<h3 id="start-server">Start Server</h3>
<p>To start the server, you can run the following command.</p>
<pre><code><span class="hljs-comment"># for mac and Linux users</span>
<span class="hljs-attribute">python3</span> manage.py runserver

<span class="hljs-comment"># for windows users</span>
python manage.py runserver
</code></pre><p>terminal
Now go to <a target="_blank" href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>, and you'll see you Django project up and running. This is the default page of the index. You'll learn how to serve your own HTML page later in this post.</p>
<p>Since we are done with the project setup and our server is started now, we can move on to creating our <strong><code>app</code></strong> for the contact form.</p>
<p>You might be thinking that we have already created a project above using the <code>django-admin</code> command, then why are we going to create a new app.</p>
<p>The answer is simple.</p>
<blockquote>
<p>In Django, everything is an app. Whether you want to create a blog, or you want to create e-commerce. Everything is an <strong>app</strong>.</p>
</blockquote>
<h2 id="create-a-contact-app">Create a contact app</h2>
<p>Now to create a contact app, we'll run the following command in the same directory.</p>
<p>Don't get confused with the directory hierarchy. They are very straight forward. You just need to keep things in mind the way they are.</p>
<p>For running these commands, you don't need to terminate your running server. You can open a new terminal in the same directory and then you can activate the environment there and then you can use any of these commands without any problem.</p>
<pre><code><span class="hljs-comment"># for mac and Linux </span>
<span class="hljs-attribute">python3</span> manage.py startapp contact

<span class="hljs-comment"># for windows</span>
python manage.py startapp contact
</code></pre><p>terminal
Now you have your <code>contact</code> app ready, and we can now move to the next part.</p>
<p>But before moving forward, let's revise the points as they are very confusing at the beginning.</p>
<ol>
<li>First, we installed a python package that helps us to create our virtual env.</li>
<li>Next, we created a new folder named <strong>myenv</strong> inside which we created our virtual environment using <strong>pipenv shell.</strong></li>
<li>After that, we installed Django in our virtual env.</li>
<li>We then created a new Django project named <strong>contactform</strong> using <code>django-admin startproject contactform</code></li>
<li>Next, we changed our directory and opened contactform, and inside that, we have our project files from contactform and a <code>manage.py</code> file.</li>
<li>We then started the server so that our project will be live and can be seen in the browser.</li>
<li>And after this, we created a new app for the contact form.</li>
</ol>
<h3 id="handling-urls">Handling URLs</h3>
<p>To handle all the URLs, Django has URL dispatcher which handles all the endpoints. This means that, whether you want to go the root URL or at <code>/admin</code>, everything is being handled by Django URL dispatcher.</p>
<p>Here we want to handle our URLs by the <code>urls.py</code> of our contact app but we don’t have any <code>urls.py</code> file in our app’s directory. So we need to create one.</p>
<p>Create a new <code>urls.py</code> file inside the contact app directory.</p>
<p>Open your <strong>contactform’s</strong><code>urls.py</code> file and import <strong><code>include</code></strong>from <code>django.urls</code>. Now inside <code>urlpatterns</code> array, add <code>path('', include('contact.urls'))</code> as shown in the below code.</p>
<pre><code><span class="hljs-string">"""contactform URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""</span>
<span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path, include
<span class="hljs-comment"># here I have imported include from django.urls</span>

urlpatterns = [
    path(<span class="hljs-string">'admin/'</span>, admin.site.urls),
    path(<span class="hljs-string">''</span>, include(<span class="hljs-string">'contact.urls'</span>))
]
<span class="hljs-comment">#I have also added a new path which will be handled by the urls.py file of my contact directory</span>
</code></pre><p>Now what is happening here is we are telling our project’s <code>urls.py</code> file that if any user comes with the request of root URL or <code>/</code>, tell him to meet contact’s <code>urls.py</code>.</p>
<p>Now inside app's <code>urls.py</code>, add the following code.</p>
<pre><code><span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> <span class="hljs-keyword">admin</span>
<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> <span class="hljs-type">path</span>

# we need <span class="hljs-keyword">to</span> <span class="hljs-keyword">import</span> views <span class="hljs-keyword">from</span> our contact app
<span class="hljs-keyword">from</span> contact <span class="hljs-keyword">import</span> views

urlpatterns = [
  path(<span class="hljs-string">''</span>, views.<span class="hljs-keyword">index</span>, <span class="hljs-type">name</span>=<span class="hljs-string">'index'</span>),
]
</code></pre><p>When it meets contact’s <code>urls.py</code> file, the URL dispatcher of the contact app checks for matching path. If any path matches with the path defined in the <code>views.py</code> file our app, then the request is served with the defined response. </p>
<p>We have named our defined path as <code>name='index'</code>. This is up to you what you want to name the path which you have defined.</p>
<p>Since we don’t have any path defined inside our <code>views.py</code> file, we need to define a path in our app’s <code>views.py</code> file. </p>
<p>Below is the code that will help us to serve any response if the request is for <code>/</code>. Replace the code of <code>views.py</code> file with the below code.</p>
<pre><code><span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render, HttpResponse

<span class="hljs-comment"># Create your views here.</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span>(<span class="hljs-params">request</span>):</span>
  <span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">'Working'</span>)
</code></pre><p>Here I have not served any static Html file but I'll do that later in this post. </p>
<p>Similarly, you can create some other path inside your app's <code>urls.py</code> file and you can define the method that will handle the request inside the <code>views.py</code> file.</p>
<p>These methods take the request as a parameter and don’t forget to import <code>HttpResponse</code> from <code>django.shortcuts</code>.</p>
<p>Now, check your root endpoint, it will show your <code>HttpResponse</code> which you’ve created and not the default response of Django.</p>
<p>Here we have used <code>HttpResponse</code> to render some basic string response inside <code>views.py</code> file. The <code>views.py</code> also has <code>import render</code> but you might be thinking why to import it when we are not using it.</p>
<p>To use render, we need to define the path of templates directory first and then only we can use it to render our templates.</p>
<p>So our next step is to create two new directories, <strong>static </strong>and <strong>templates</strong> in the same directory where <code>manage.py</code>, app’s file and project’s files are stored.</p>
<p><em>The Django application serves static files like static CSS files or the JS files or any other kind of static files from its static directory.</em></p>
<p>To use <em>return render request</em>, we need some kind of HTML template, and that needs to be stored inside the templates directory.</p>
<blockquote>
<p><strong><em>Keep one thing in mind, people can see your static files or the files stored in the static directory but they can’t see your python code. So don’t keep any file that has some important details inside the static directory.</em></strong></p>
</blockquote>
<p>Now open your <code>settings.py</code> file and paste the following code just below the <code>STATIC_URL = '/static/'</code> as shown in the below code.</p>
<pre><code><span class="hljs-comment"># Static files (CSS, JavaScript, Images)</span>
<span class="hljs-comment"># https://docs.djangoproject.com/en/3.1/howto/static-files/</span>

<span class="hljs-attr">STATIC_URL</span> = <span class="hljs-string">'/static/'</span>

<span class="hljs-comment"># Copy from below</span>
<span class="hljs-comment"># Static directory path</span>
<span class="hljs-attr">STATICFILES_DIRS</span> = [
    BASE_DIR / <span class="hljs-string">"static"</span>,
    <span class="hljs-string">'/var/www/static/'</span>,
]
</code></pre><p>You just need to paste the <code>STATICFILES_DIRS</code> and not the complete code.</p>
<p>You can also read more about managing static files from the link given below.</p>
<p><a target="_blank" href="https://docs.djangoproject.com/en/3.1/howto/static-files/">Managing static files</a></p>
<p>Now let’s try to serve any static file from the static directory. Copy any image and paste it in the static directory and open its path in the browser.</p>
<p><code>http://127.0.0.1:8000/static/demo.txt</code></p>
<p>I’ve created a demo.txt file and stored it in a static directory. Similarly, you can store any file and it can be served using the same static URL. Make sure you are using the correct URL.</p>
<h3 id="templates-path-configuration">Templates path configuration</h3>
<p>Our next step is to configure the path of templates directory to use our HTML templates. You just need to copy the following code <code>BASE_DIR / "templates"</code> and paste it in the <code>TEMPLATES</code> array’s <code>'DIRS': [ BASE_DIR / "templates" ],</code> or as shown in the code below.</p>
<pre><code><span class="hljs-comment"># See the code in line number 7</span>
<span class="hljs-comment"># Make sure your code looks same as mine</span>

<span class="hljs-attr">TEMPLATES</span> = [
    {
        <span class="hljs-string">'BACKEND'</span>: <span class="hljs-string">'django.template.backends.django.DjangoTemplates'</span>,
        <span class="hljs-string">'DIRS'</span>: [ BASE_DIR / <span class="hljs-string">"templates"</span> ],
        <span class="hljs-string">'APP_DIRS'</span>: <span class="hljs-literal">True</span>,
        <span class="hljs-string">'OPTIONS'</span>: {
            <span class="hljs-string">'context_processors'</span>: [
                <span class="hljs-string">'django.template.context_processors.debug'</span>,
                <span class="hljs-string">'django.template.context_processors.request'</span>,
                <span class="hljs-string">'django.contrib.auth.context_processors.auth'</span>,
                <span class="hljs-string">'django.contrib.messages.context_processors.messages'</span>,
            ],
        },
    },
]
</code></pre><p>This will configure the path of the template directory and you are now ready to serve your Html templates.</p>
<p>Now create a new <code>index.html</code> file inside your <code>templates</code> directory. Now open your <code>views.py</code> file and here we are going to use <code>return render(request, ‘index.html’)</code>.</p>
<p>Below is the code to use it in the views.</p>
<pre><code><span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render

<span class="hljs-comment"># Create your views here.</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span>(<span class="hljs-params">request</span>):</span>
  <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'index.html'</span>)
</code></pre><p>We can now remove <code>HttpResponse</code> as we no longer use it in our <code>views.py</code> file.</p>
<h3 id="using-variables-with-templates">Using variables with templates</h3>
<p>We can also use variables in our Html template to send any information that we want to show on our Html template.</p>
<p>To use any variable, we use <code>{{ variable_name }}</code> in our template.</p>
<pre><code><span class="hljs-comment">&lt;!-- Copy the following code and paste it in your HTML template --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>I am {{ name }}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre><p>And inside my <code>views.py</code> file, I can pass this variable with template.</p>
<pre><code><span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render

<span class="hljs-comment"># Create your views here.</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span>(<span class="hljs-params">request</span>):</span>
  <span class="hljs-comment"># create your variable here</span>
  context = {
    <span class="hljs-string">'name'</span> : <span class="hljs-string">'Pratik'</span>
  }
  <span class="hljs-comment"># pass it here with the html template</span>
  <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'index.html'</span>, context)
</code></pre><h3 id="django-admin-panel">Django Admin Panel</h3>
<p>Now you are done with the templating, we can now move to the admin panel. Visit <code>http://127.0.0.1:8000/admin/</code> and you’ll see a login form. Try login and it will give you an error <code>no such table: auth_user</code>.</p>
<p>This error is because we don’t have any table in our database as of now. To make the changes in our database, we need to run two terminal commands.</p>
<pre><code><span class="hljs-comment"># fro Mac and Linux users</span>
<span class="hljs-attribute">python3</span> manage.py makemigrations

<span class="hljs-comment"># for Windows users</span>
python manage.py makemigrations
</code></pre><p>terminal
And the second command</p>
<pre><code><span class="hljs-comment"># fro Mac and Linux users</span>
<span class="hljs-attribute">python3</span> manage.py migrate

<span class="hljs-comment"># for Windows users</span>
python manage.py migrate
</code></pre><p>terminal
When you’ll run the first command, this will not show any changes. But when you’ll run the second command, you’ll see some changes in the terminal.</p>
<p>This is because Django uses some default schema or table for user authentication. Now when you try to log in, this time it will not show the same error.</p>
<p>It will ask you to enter the correct username and password.</p>
<h3 id="creating-superuser">Creating superuser</h3>
<p>We know why our id and password is wrong as there is no user registered by default.</p>
<p>So we need to create a new <strong><em>superuser</em></strong>. Below is the command to create a new superuser. This will ask you for some basic information and a new superuser will be created.</p>
<pre><code><span class="hljs-comment"># fro Mac and Linux users</span>
<span class="hljs-attribute">python3</span> manage.py createsuperuser

<span class="hljs-comment"># for Windows users</span>
python manage.py createsuperuser
</code></pre><p>terminal
You can now use that credentials to log in to the admin panel. All our database model, information stored in database can be seen in the admin panel.</p>
<p>You might be thinking how to change the title and header of our admin panel and name it as per our application as Django administration doesn’t look professional. This can be changed by adding these code in your project’s urls.py file.</p>
<pre><code><span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> <span class="hljs-keyword">admin</span>
<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> <span class="hljs-type">path</span>, <span class="hljs-keyword">include</span>

# <span class="hljs-keyword">Add</span> these three lines <span class="hljs-keyword">of</span> code <span class="hljs-keyword">in</span> your urls.py file same <span class="hljs-keyword">as</span> I did
<span class="hljs-keyword">admin</span>.site.site_header = "Contact Admin"
<span class="hljs-keyword">admin</span>.site.site_title = "Contact Admin Portal"
<span class="hljs-keyword">admin</span>.site.index_title = "Welcome to Contact Portal"

urlpatterns = [
    path(<span class="hljs-string">'admin/'</span>, <span class="hljs-keyword">admin</span>.site.urls),
    path(<span class="hljs-string">''</span>, <span class="hljs-keyword">include</span>(<span class="hljs-string">'contact.urls'</span>))
]
</code></pre><blockquote>
<p><strong>Note</strong>: These codes need to be pasted in your <strong>project </strong>level <code>urls.py</code> file and not in <strong>app-level</strong><code>urls.py</code> file.</p>
</blockquote>
<p>Now check your admin panel. This will look much better now after the name change.</p>
<h2 id="model-class">Model class</h2>
<p>We are done with the form setup. Let us now create a model class for saving the data from our contact form.</p>
<p>But before that, let’s understand what is a model?</p>
<blockquote>
<p><strong><em>A database model is a type of data model that determines in which manner data can be stored and manipulated.</em></strong></p>
</blockquote>
<p><em>Ex: Relational model</em></p>
<p>Now inside your <code>models.py</code> file, let us create a <strong>Contact </strong>model. We need to <code>import models</code> from <code>django.db</code> and then write our model class. Copy the below code to create a contact model.</p>
<pre><code><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-comment"># Create your models here. </span>
<span class="hljs-comment"># Note that I have used an uppercase letter for class name</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Contact</span>(<span class="hljs-params">models.Model</span>):</span>
  name = models.CharField(max_length=<span class="hljs-number">122</span>)
  email = models.CharField(max_length=<span class="hljs-number">120</span>)
  desc = models.TextField()
  date = models.DateField()
</code></pre><p>Now let us run <strong>makemigrations </strong>command to <strong>register </strong>all the changes in the model. </p>
<pre><code><span class="hljs-comment"># fro Mac and Linux users</span>
<span class="hljs-attribute">python3</span> manage.py makemigrations

<span class="hljs-comment"># for Windows users</span>
python manage.py makemigrations
</code></pre><p>This command will tell Django to make a note of all the changes I’ve made in the model.</p>
<p>This will not make any new table or make any changes in the database. This will only register the changes that are made and these changes will come into effect when we run the <code>migrate</code> command.</p>
<p>But for your surprise, the <code>makemigrations</code> will still show that <code>No changes detected</code>. </p>
<p>But how is this possible? We have made changes in the model, but this is still showing that the model is still the same.</p>
<p>The reason is simple. We have made changes, but we have not registered our model yet to make the changes.</p>
<p>To register our model, open your <code>admin.py</code> file and import <code>Contact</code> from <code>contact.models</code>. Or you can paste the following code in your admin.py file.</p>
<pre><code><span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> contact.models <span class="hljs-keyword">import</span> Contact  

<span class="hljs-comment"># Register your models here.</span>
admin.site.register(Contact)
</code></pre><p>This will register your model with Django but you need to register your app in <code>INSTALLED_APPS</code> inside <code>settings.py</code> file.</p>
<p>Go to your <code>apps.py</code> file inside your <strong>contact</strong> app directory, copy the name of the class and go to settings and inside <code>INSTALLED_APPS</code>, paste it there as <code>‘contact.apps.ContactConfig’</code>  or as shown in the code below.</p>
<pre><code><span class="hljs-comment"># here as shown in the first line inside the array</span>

<span class="hljs-attr">INSTALLED_APPS</span> = [
    <span class="hljs-string">'contact.apps.ContactConfig'</span>,
    <span class="hljs-string">'django.contrib.admin'</span>,
    <span class="hljs-string">'django.contrib.auth'</span>,
    <span class="hljs-string">'django.contrib.contenttypes'</span>,
    <span class="hljs-string">'django.contrib.sessions'</span>,
    <span class="hljs-string">'django.contrib.messages'</span>,
    <span class="hljs-string">'django.contrib.staticfiles'</span>,
]
</code></pre><p>Now when you’ll try to run the <code>makemigrations</code> command, this will make some changes that you will see in your terminal and inside your project directory.</p>
<pre><code><span class="hljs-comment"># fro Mac and Linux users</span>
<span class="hljs-attribute">python3</span> manage.py makemigrations

<span class="hljs-comment"># for Windows users</span>
python manage.py makemigrations
</code></pre><p>And when you’ll run <code>migrate</code> command, this will generate a new table named contact that can be seen in the admin panel.</p>
<pre><code><span class="hljs-comment"># fro Mac and Linux users</span>
<span class="hljs-attribute">python3</span> manage.py migrate

<span class="hljs-comment"># for Windows users</span>
python manage.py migrate
</code></pre><p>Visit your admin panel and there you'll see the contact table like this.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1607788736022/ugVYz5lOV.png" alt="admin.png" /></p>
<p>We can save data from the admin panel directly but we are not going to do that here. We will submit our form data using the Html form we have created in our HTML file.</p>
<p>To accept the data for our model field, we need to write our logic inside our <code>views.py</code> file and we are good to go.</p>
<p>Now inside our <code>views.py</code> file, we need to paste the following code.</p>
<pre><code><span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render
<span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime
<span class="hljs-keyword">from</span> contact.models <span class="hljs-keyword">import</span> Contact

# <span class="hljs-keyword">Create</span> your views here.
def <span class="hljs-keyword">index</span>(request):
  <span class="hljs-keyword">if</span> (request.<span class="hljs-keyword">method</span> == <span class="hljs-string">'POST'</span>):
    <span class="hljs-type">name</span> = request.POST.<span class="hljs-keyword">get</span>(<span class="hljs-string">'name'</span>)
    email = request.POST.<span class="hljs-keyword">get</span>(<span class="hljs-string">'email'</span>)
    <span class="hljs-keyword">desc</span> = request.POST.<span class="hljs-keyword">get</span>(<span class="hljs-string">'desc'</span>)
    contact = Contact(<span class="hljs-type">name</span>=<span class="hljs-type">name</span>, email=email, <span class="hljs-keyword">desc</span>=<span class="hljs-keyword">desc</span>, <span class="hljs-type">date</span>=datetime.today())
    contact.save()
  <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'index.html'</span>)
</code></pre><p>Let us understand what we are doing with the following code.</p>
<ol>
<li>We have imported our model class and datetime.</li>
<li>Next, we are going to check if the request is <code>GET</code> or <code>POST</code>.</li>
<li>If the request is <code>GET</code>, we simply return our Html template.</li>
<li>If the request is <code>POST</code>, we are fetching <code>name</code>, <code>email</code>, <code>desc</code> from the form and we are passing it in the constructor of our model class and in this way, they will be stored in our table when we call the <code>save</code> method.</li>
</ol>
<p>We can now try to submit our form. But wait, now this is showing that <code>CSRF verification failed. Request aborted</code>.</p>
<p>What does that mean?</p>
<p>The CSRF middleware and template tag provides easy-to-use protection against Cross-Site Request Forgeries. You can learn more about it here.</p>
<p><a target="_blank" href="https://docs.djangoproject.com/en/3.1/ref/csrf/">Cross Site Request Forgery protection</a></p>
<p>This error occurred because of missing csrf token. We can add this code <code>{% csrf_token %}</code> inside our <code>&lt;form&gt;</code> tag or as shown below.</p>
<pre><code>&lt;form action="/" <span class="hljs-keyword">method</span>="POST"&gt;
  {% csrf_token %}
  &lt;div <span class="hljs-keyword">class</span>="form-group"&gt;
    &lt;label <span class="hljs-keyword">for</span>="name"&gt;<span class="hljs-keyword">Full</span> <span class="hljs-type">Name</span>&lt;/label&gt;
    &lt;<span class="hljs-keyword">input</span> <span class="hljs-keyword">type</span>="text" <span class="hljs-keyword">class</span>="form-control" <span class="hljs-type">name</span>="name" id="name" placeholder="Your Name"&gt;
  &lt;/div&gt;
  &lt;div <span class="hljs-keyword">class</span>="form-group"&gt;
    &lt;label <span class="hljs-keyword">for</span>="email"&gt;Email address&lt;/label&gt;
    &lt;<span class="hljs-keyword">input</span> <span class="hljs-keyword">type</span>="email" <span class="hljs-type">name</span>="email" <span class="hljs-keyword">class</span>="form-control" id="email" placeholder="name@example.com"&gt;
  &lt;/div&gt;
  &lt;div <span class="hljs-keyword">class</span>="form-group"&gt;
    &lt;label <span class="hljs-keyword">for</span>="message"&gt;Your message&lt;/label&gt;
    &lt;textarea <span class="hljs-keyword">class</span>="form-control" id="message" <span class="hljs-type">name</span>="desc" <span class="hljs-keyword">rows</span>="3"&gt;&lt;/textarea&gt;
  &lt;/div&gt;
  &lt;<span class="hljs-keyword">input</span> <span class="hljs-keyword">type</span>="submit" <span class="hljs-keyword">class</span>="btn btn-primary" <span class="hljs-keyword">value</span>="Submit"&gt;
&lt;/form&gt;
</code></pre><p>If you want to change the name of user who sent you the mail, you can do it by adding this small code inside your <code>models.py</code> file.</p>
<pre><code><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

<span class="hljs-comment"># Create your models here. </span>
<span class="hljs-comment"># Note that I have used an uppercase letter for class name</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Contact</span>(<span class="hljs-params">models.Model</span>):</span>
  name = models.CharField(max_length=<span class="hljs-number">122</span>)
  email = models.CharField(max_length=<span class="hljs-number">120</span>)
  desc = models.TextField()
  date = models.DateField()
  <span class="hljs-comment"># code to show name of the person who sent you the message</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_str_</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-keyword">return</span> self.name
</code></pre><p>Now, the admin panel will show you the name of the sender who has sent you the message. </p>
<p>You can download the code from my GitHub repo from the blow link.</p>
<p><a target="_blank" href="https://github.com/ThePratikSah/django-contact">ThePratikSah on GitHub</a></p>
<p>Well, this was all for today. I know this post is way too long but this is an in-depth guide for Django contact form.</p>
<p>Thanks for your time. If you found this post helpful😊, please share this with your friends.</p>
<p>If you stuck into some kind of problem, feel free to comment below. I'll be happy to help you🙂.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding React State and setState]]></title><description><![CDATA[The state is the place where we store the data. React components have state built-in.
All the property values that a component has, is stored in the state. When a state object changes, the component is re-rendered.
Creating State in React
The state i...]]></description><link>https://blog.pratik.dev/understanding-react-state-and-setstate</link><guid isPermaLink="true">https://blog.pratik.dev/understanding-react-state-and-setstate</guid><category><![CDATA[React]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Tue, 04 Aug 2020 16:13:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607317151825/nUqAqx1ys.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The state is the place where we store the data. React components have state built-in.
All the property values that a component has, is stored in the state. When a state object changes, the component is re-rendered.</p>
<h2 id="creating-state-in-react">Creating State in React</h2>
<p>The <strong>state </strong>is defined inside <code>React.Component</code>. Below code is an example of a stateful component in React.</p>
<pre><code><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom"</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">header</span>: <span class="hljs-string">"Pratik"</span>,
    };
  }

  changeHeader = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">this</span>.setState({<span class="hljs-attr">header</span>: <span class="hljs-string">'Pratik Sah'</span>});
  }

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{this.state.header}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.changeHeader}</span>&gt;</span>Change<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}

ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>));
</code></pre><p>Once the class extends <code>Component</code>, we need to call the <code>super();</code> method inside the constructor. This helps us to call the parent's constructor.</p>
<p><code>this.state</code></p>
<p>Now we can use the <strong>state</strong> property to store our app's current state. </p>
<p>For example, here I tried to store header as "Pratik"</p>
<pre><code><span class="hljs-keyword">this</span>.state = {
  <span class="hljs-string">"header"</span>: <span class="hljs-string">"Pratik"</span>,
}
</code></pre><p>and in my <code>&lt;h1&gt;&lt;/h1&gt;</code> tag, I've used is to display my name.</p>
<p><code>this.state.header</code> inside <code>h1</code> tag is going to return the value of header as 'Pratik'.</p>
<p>After that, I've created a button to manipulate the value of the state.</p>
<p>On clicking the button, a function named <code>changeHeader</code> will be called and this will change the value inside the state with the help of <code>setState()</code> method. The setState method is also defined inside <code>React.Component</code>.</p>
<p>Inside the <code>changeHeader</code> method:</p>
<pre><code><span class="hljs-function"><span class="hljs-title">changeHeader</span> = <span class="hljs-params">()</span> =&gt;</span> {
  <span class="hljs-built_in">this</span>.setState({header: <span class="hljs-string">'Pratik Sah'</span>});
}
</code></pre><p>Now this will change the state from 'Pratik' to 'Pratik Sah' on button click.</p>
<p>This is how a React state works. I hope you've understood the concept of <code>state</code> and <code>setState</code> and if you have found this post helpful, please share it with your friends.</p>
<p>If you stuck in any kind of error, feel free to comment your doubts in the comment section below. </p>
<p>If you liked this post please mark this post as Recommend by clicking the ❤️ button below in the comments section. This will help me a lot.</p>
<p>Thanks for your time. See you in my next post. Take care and happy coding✌️.</p>
]]></content:encoded></item><item><title><![CDATA[How to render content conditionally in React JS]]></title><description><![CDATA[Sometimes we are in a situation where we want to render any particular content only and if the condition is not satisfied, we may want to hide the content.
Let us understand this with an example. Suppose we are inside our profile section. We want to ...]]></description><link>https://blog.pratik.dev/render-content-conditionally-in-react-js</link><guid isPermaLink="true">https://blog.pratik.dev/render-content-conditionally-in-react-js</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Pratik Sah]]></dc:creator><pubDate>Fri, 31 Jul 2020 16:11:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1607316952910/JKveJyXHp.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sometimes we are in a situation where we want to render any particular content only and if the condition is not satisfied, we may want to hide the content.</p>
<p>Let us understand this with an example. Suppose we are inside our profile section. We want to see the details from our profile page but we don't want to see the form below that to edit the information at the same time. It'll look a bit annoying.</p>
<p>We want to see the edit form only when we want to edit any information or when we want to add any information.</p>
<p>This can be toggled on a button click. This looks easy right. Yes, but the implementation part is a bit tricky.</p>
<p>We can toggle visibility in two different methods.</p>
<ol>
<li>Using the <strong>ternary operator</strong></li>
<li>Using the <strong>if statement</strong></li>
</ol>
<p>It's up to you which one you want to use. I prefer the second one. I' tell you why but let me show you both the ways first.</p>
<p><strong>For using any of the methods, we need to add a visibility state that is going to hold the toggle state.</strong></p>
<p>So, let's add a visibility state.</p>
<p><code>const [visible, setVisible] = useState(() =&gt; true);</code></p>
<blockquote>
<p>Note: Here I'll be using <a target="_blank" href="https://reactjs.org/docs/hooks-intro.html">React Hooks</a> for implementing state but this can be done on both class as well as in functional component.</p>
</blockquote>
<p>Here I've kept the state <strong>visible</strong> at the initial stage. We will change the state when we will try to toggle the visibility.</p>
<h2 id="using-the-ternary-operator">Using the Ternary Operator</h2>
<p>Next inside the return statement, we are going to use the <strong><em>ternary</em></strong> operator of javascript.</p>
<p><code>condition ? statement1 : statement2;</code> </p>
<p>I hope all of you are aware of this ternary operator. If not, it's fine. You can learn it <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">here</a>. We are using ternary operator because we can't use <strong>if</strong> block here.</p>
<p>Now in place of condition, we will put the current toggle state and in place of <strong>statement1,</strong> we will keep the <strong>JSX</strong> content which we want to show. </p>
<p>In place of <strong>statement2, </strong>we will keep <code>null</code>. Null will hide the content from there.</p>
<p>We also require a button to toggle the state and we have to handle <code>onClick</code> of the button for the visibility.</p>
<p>Here is the code for the same.</p>
<pre><code><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> HooksEx = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [visible, setvisible] = useState(<span class="hljs-function">() =&gt;</span> <span class="hljs-literal">true</span>);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
        <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> {
          // here I am toggling the visibility using ! operator
          setvisible((visible) =&gt; !visible);
        }}
      &gt;
        Toggle Visibility
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      {visible ? <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Pratik<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> : null}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> HooksEx;
</code></pre><p>Next, we are going to use the <strong><em>if statement</em></strong> to hide the content and this method is more cleaner way of doing the same.</p>
<h2 id="using-the-if-statement">Using the if statement</h2>
<p>When we are using this method, we have to create a new variable and we have to assign <strong>null</strong> in that variable.</p>
<p><code>let inputValue = null;</code></p>
<p>Now inside <strong>if</strong> condition, we will put the current toggle state and in place of statement body, we will keep the <strong>JSX</strong> content which we want to show.</p>
<p>Similarly, we will use a <code>button</code> to toggle the state and we have to handle <code>onClick</code> of the button for the visibility.</p>
<p>Here is the code for the same.</p>
<pre><code><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> HooksEx = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [visible, setvisible] = useState(<span class="hljs-function">() =&gt;</span> <span class="hljs-literal">true</span>);

  <span class="hljs-keyword">let</span> input = <span class="hljs-literal">null</span>;

  <span class="hljs-keyword">if</span> (visible) {
    input = (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Pratik<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
        <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> {
          setvisible((visible) =&gt; !visible);
        }}
      &gt;
        Toggle Visibility
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      {input}
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> HooksEx;
</code></pre><p>This is going to toggle our content whatever we have kept inside the statement of the conditionals.</p>
<p>Well, this was all for today. Thanks for your time. If you found this post helpful😊, please share this with your friends. </p>
<p>If you stuck into some kind of problem, feel free to comment below. I'll be happy to help you🙂.</p>
<p>This is Pratik and I'll meet you in my other post✌️.</p>
]]></content:encoded></item></channel></rss>