<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title>Webkoof.in | Code with Bharat Sahu</title>
        <link>https://webkoof.in/</link>
        <description>Code with Bharat Sahu! JavaScript, React, Next.js, Node.js and Firebase tutorials.</description>
        <lastBuildDate>Sat, 26 Sep 2026 07:49:23 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>Bharat Sahu using Feed for NextJS Blog</generator>
        <language>en</language>
        <image>
            <title>Webkoof.in | Code with Bharat Sahu</title>
            <url>https://webkoof.in/images/bhar4t.png</url>
            <link>https://webkoof.in/</link>
        </image>
        <copyright>All rights reserved 2026, Bharat Sahu</copyright>
        <item>
            <title><![CDATA[The Ultimate Cursor Rule for Clean React.js Components]]></title>
            <link>https://webkoof.in/articles/The-Ultimate-Cursor-Rule-for-Clean-React</link>
            <guid isPermaLink="false">https://webkoof.in/articles/The-Ultimate-Cursor-Rule-for-Clean-React</guid>
            <pubDate>Fri, 25 Sep 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Stop AI from writing messy, outdated React code. Use this native configuration file to force Cursor to generate optimized, production-ready components—no npm packages required.]]></description>
            <content:encoded><![CDATA[<h2>The Ultimate Cursor Rule for Clean React.js Components</h2>
<p>Many developers are pivoting from standard editors to <strong>Cursor AI</strong>, a powerful fork of VS Code. However, left to its own devices, AI code completion often mixes modern React with outdated 2019 patterns, uses inefficient inline styling, and defaults to bad habits like using array indices as unique keys.</p>
<p>You do not need to clean up after the AI manually. By using Cursor's native rule configuration files (<code>.mdc</code>), you can establish architectural guardrails that force the AI to write pristine code on its first try. <strong>No extra npm packages are required.</strong></p>
<hr>
<h3>The Recipe Configuration</h3>
<p>To get started, create a new folder path in your project root at <code>.cursor/rules/</code> and name the file <strong><code>react-modern.mdc</code></strong>. Copy and paste the configuration code block below exactly as written:</p>
<pre><code class="language-markdown">---
description: Rules for generating modern and clean React.js components
globs: src/**/*.js, src/**/*.jsx, components/**/*.jsx, app/**/*.jsx
---

# Modern React.js Rules
- **Functional Only:** Never generate class components. Use clean arrow functions (`const Component = () => {}`).
- **Export Pattern:** Use explicit named exports instead of default exports to ensure seamless IDE auto-imports.
- **Props Destructuring:** Always destructure props directly inside the component function signature.
- **Keys in Arrays:** Always provide a stable, unique item identifier (`item.id`) as the key prop when mapping arrays. Never default to the array index.
- **Styling:** Avoid inline `style={{}}` attributes. Use utility-first classes (like Tailwind CSS) or semantic layout patterns.
</code></pre>
<hr>
<h3>Why it Matters: Before vs After</h3>
<p>When you save this <code>.mdc</code> file, Cursor automatically scans your workspace workspace and updates its system prompts for your target files. Here is a direct look at how this changes the output quality:</p>
<h4>Before Applying the Rule (Standard AI Output)</h4>
<p>Without instructions, LLMs often default to generic, unoptimized code styles:</p>
<pre><code class="language-jsx">import React from 'react';

export default function Dashboard(props) {
    const user = props.user;
    return (
      &#x3C;div style={{ padding: '20px', border: '1px solid #ccc' }}>
        &#x3C;h1>Welcome, {user.name}&#x3C;/h1>
          &#x3C;ul>
            {user.items.map((item, index) => (
              &#x3C;li key={index}>{item.name}&#x3C;/li>
            ))}
          &#x3C;/ul>
      &#x3C;/div>
    );
}
</code></pre>
<h4>After Applying the Rule (Cursor AI Output)</h4>
<p>With your new recipe rule file active in the folder background, the AI naturally adheres to clean architectural principles:</p>
<pre><code class="language-jsx">import React from 'react';

export const Dashboard = ({ user }) => {
  const { name, items } = user;
  return (
    &#x3C;div className="p-5 border border-gray-200 rounded-lg">
      &#x3C;h1 className="text-xl font-bold">Welcome, {name}&#x3C;/h1>
      &#x3C;ul className="mt-4 space-y-2">
        {items.map((item) => (
          &#x3C;li key={item.id} className="text-gray-700">
            {item.name}
          &#x3C;/li>
        ))}
      &#x3C;/ul>
    &#x3C;/div>
  );
};
</code></pre>
<hr>
<h3>How This Works Under the Hood</h3>
<p>The secret lies in the <code>.mdc</code> header block:</p>
<ul>
<li><strong><code>globs</code></strong>: Tells Cursor exactly which folders and extensions to monitor.</li>
<li><strong>Zero Overhead</strong>: This runs entirely inside Cursor's internal token context. It does not impact your application bundle size, production speeds, or local development environments.</li>
</ul>
<p>Drop this file into your workspace and watch your AI coding velocity instantly double with cleaner results.</p>
<h4>References:</h4>
<p>To learn more about optimizing your AI workflows or to explore deeper React patterns, check out these excellent resources:</p>
<ul>
<li>Official Configuration Guide: Read the <a href="https://cursor.com/docs/rules" title="Rules | Cursor Docs">Cursor Rules Documentation</a> to understand exactly how the <code>.mdc</code> file structure matches your project files.</li>
<li>Community Rule Marketplace: If you want inspiration for more specific development setups, browse through community-curated templates on the official <a href="https://cursor.directory/plugins/react" title="React | Cursor Directory">Cursor Directory</a>.</li>
<li>The "Token Tax" Problem: For an in-depth breakdown of why moving to modular <code>.mdc</code> files saves massive API costs compared to legacy <code>.cursorrules</code> files, read the complete guide by the <a href="https://www.vibecodingacademy.ai/blog/cursor-rules-complete-guide" title="Cursor Rules: Complete .mdc Guide &#x26; 15 Templates (2026) - Vibe Coding Academy">Vibe Coding Academy</a>.</li>
<li>React Implementation Challenges: For a humorous but highly practical look at the common bugs LLMs make without proper guidance, read <a href="https://medium.com/@Hack_hack_xanum/10-react-rules-cursor-loves-to-ignore-like-a-rebel-without-a-linter-b125085766e0" title="10 React Rules Cursor Loves to Ignore (Like a Rebel Without a Linter) - Medium">10 React Rules Cursor Loves to Ignore</a> on Medium.</li>
</ul>
]]></content:encoded>
            <author>bhar4t@outlook.com (Bharat Sahu)</author>
            <enclosure url="https://webkoof.in/img/cursor_react.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide to Upgrading Node.js: From Version 16 to 20 (Including ReactJS CRA 5 Fixes)]]></title>
            <link>https://webkoof.in/articles/nodejs-upgrade-guide-v16-to-v20-cra5</link>
            <guid isPermaLink="false">https://webkoof.in/articles/nodejs-upgrade-guide-v16-to-v20-cra5</guid>
            <pubDate>Tue, 14 Jan 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[A comprehensive guide to upgrading your Node.js version from 16 to 20, addressing common issues and fixes with CRA 5 and dependencies.]]></description>
            <content:encoded><![CDATA[<p>This document outlines the steps taken to upgrade the project from Node.js <strong>v16.16.0</strong> to <strong>v20.9.0</strong> and address related issues for a smooth migration.</p>
<h2>Stack</h2>
<p>React, Typescript, SASS, Apollo-client, CRA (create-react-app)</p>
<h3>Why Upgrade Node.js First?</h3>
<p>Upgrading Node.js first ensures compatibility with other dependencies. If dependencies are upgraded prior to the Node.js upgrade, potential conflicts could arise, requiring additional fixes later.</p>
<hr>
<h3>Steps Taken</h3>
<h4>1. Node.js Upgrade</h4>
<ul>
<li>Upgraded Node.js to <strong>v20.9.0 LTS</strong> from <strong>v16.16.0</strong>.</li>
<li>Removed <code>node_modules</code> and reinstalled dependencies after the upgrade.</li>
<li>Kept npm version at <strong>9.6.5</strong> as <code>npm@11.0.0</code> requires a Node.js version higher than v20 LTS.</li>
</ul>
<h4>2. Workaround for Initial Issues</h4>
<ul>
<li>Resolved <code>Node.js ERR_OSSL_EVP_UNSUPPORTED</code> using in windows:
<pre><code class="language-bash">set NODE_OPTIONS=--openssl-legacy-provider
</code></pre>
</li>
</ul>
<p>For Linux or Mac users can use <code>export</code> keyword instead of <code>set</code> before start start the app.
However, avoided this workaround by updating dependencies.</p>
<h4>3. Dependency Updates</h4>
<p>Ran the following command to address dependency issues:</p>
<pre><code class="language-bash">npm audit fix --dev
</code></pre>
<p>Once the command executed, multiple dependencies updated along with <code>react-scripts</code> which was <code>v4.0.3</code>, now it is <code>^5.0.1</code>. Changed multiple codes related to my listed dependencies in <code>package.json</code>, this will be different in case of your application.</p>
<hr>
<h3>Errors and Fixes</h3>
<ol>
<li>
<p><strong>Warning on Startup</strong>:</p>
<pre><code>One of your dependencies, babel-preset-react-app, is importing the "@babel/plugin-proposal-private-property-in-object" package without declaring it in its dependencies. This is currently working because "@babel/plugin-proposal-private-property-in-object" is already in your node_modules folder for unrelated reasons, but it may break at any time.

babel-preset-react-app is part of the create-react-app project, which is not maintianed anymore. It is thus unlikely that this bug will ever be fixed. Add "@babel/plugin-proposal-private-property-in-object" to your devDependencies to work around this error. This will make this message go away.
</code></pre>
<p></p>
<ul>
<li><strong>Fix</strong>: Added <code>@babel/plugin-proposal-private-property-in-object</code> to devDependencies.</li>
<li><strong>Result</strong>: Warning resolved.</li>
</ul>
</li>
<li>
<p><strong>SVG Style Issue</strong> And <strong>Redundant Code</strong>:</p>
<ul>
<li>Removed unsupported styles (<code>/**/</code>) in <code>gba_gray.svg</code>.</li>
<li>Removed unnecessary <code>return</code> statements. earlier these was not throwing any error.</li>
</ul>
</li>
<li>
<p><strong>TinyMCE Plugin Errors</strong>:</p>
<ul>
<li>Errors for plugins: <code>"hr"</code>, <code>"spellchecker"</code>, <code>"template"</code>, <code>"print"</code>, <code>"paste"</code>, as the package has upgraded after npm audit fix command.</li>
<li><strong>Fix</strong>: Removed explicit imports from the file the editor has initialised, in my case it was in file <code>WYSIWYGEditor/index.tsx</code>.</li>
<li>Reference: <a href="https://www.tiny.cloud/blog/fixing-plugin-errors/">TinyMCE Docs</a></li>
</ul>
</li>
<li>
<p><strong>SCSS Warnings</strong> / <strong>SASS Path Configuration</strong>:</p>
<ul>
<li>Added environment variables:
<pre><code class="language-env"> REACT_APP_SASS_PATH=./src/styles
 SASS_PATH=./src/styles
</code></pre>
</li>
<li>Replaced relative paths in <strong>265</strong> SCSS files, which was quite easy as it appearing in terminal directly in warning message, what we need to do.
<pre><code class="language-scss"> @import 'includes';
</code></pre>
With:
<pre><code class="language-scss"> @import 'src/styles/includes';
</code></pre>
</li>
</ul>
</li>
<li>
<p><strong>Buffer Issue</strong> / <strong>Polyfill Issue</strong>:</p>
<ul>
<li>Imported <code>Buffer</code> explicitly after installation due to <code>react-scripts</code> v5 doesn't support some core modules. listed other important dependencies for polyfills for you it may help.</li>
</ul>
<pre><code class="language-json">  "buffer": "npm:buffer@^6.0.3",
  "crypto": "npm:crypto-browserify@^3.12.0",
  "http": "npm:stream-http@^3.2.0",
  "https": "npm:https-browserify@^1.0.0",
  "stream": "npm:stream-browserify@^3.0.0",
  "util": "npm:util@^0.12.5",
  "zlib": "npm:browserify-zlib@^0.2.0"
</code></pre>
</li>
<li>
<p><strong>ESLint Rule Update</strong>:</p>
<ul>
<li>
<p>Added rule in <code>.eslintrc.js</code>:</p>
<pre><code class="language-json">'@typescript-eslint/no-non-null-asserted-optional-chain': 'off'
</code></pre>
</li>
<li>
<p>Updated the multiple pacakages related to eslint/prettier as react-scripts 5 includes eslint under the hood and to utilize in-built eslint and also to get rid of below issue:</p>
<pre><code class="language-bash">  ERROR in [eslint] Failed to load config "prettier" to extend from.
  Referenced from: C:\Users\path\to\.eslintrc.js
</code></pre>
<p></p>
<p>Removed:</p>
<ul>
<li><code>eslint-config-standard</code>: <code>^16.0.3</code></li>
<li><code>eslint-plugin-import</code>: <code>^2.23.4</code></li>
<li><code>eslint-plugin-promise</code>: <code>^5.1.0 </code></li>
<li><code>eslint-plugin-react</code>: <code>^7.24.0</code></li>
</ul>
<p>Updated:</p>
<ul>
<li><code>prettier</code>: <code>2.1.1</code> to <code>^3.0.3</code></li>
<li><code>eslint-plugin-prettier</code>: <code>3.3.0</code> to <code>^5.2.2</code>             // Enforced using resolution/override</li>
<li><code>eslint-config-prettier</code>: <code>^8.3.0</code> to <code>^10.0.1</code>           // Added in devDependencies</li>
<li><code>pretty-quick</code>: <code>^3.1.1</code> to <code>^4.0.0</code>                      // Added in devDependencies</li>
<li><code>@typescript-eslint/eslint-plugin</code>: <code>4.28.3</code> to <code>^5.6.0</code>  // Added in devDependencies</li>
<li><code>@typescript-eslint/parser</code>: <code>4.28.3</code> to <code>^5.6.0</code>         // Added in devDependencies</li>
</ul>
<pre><code class="language-js">  // package.json (Included)
  "resolutions": {
    "eslint": "^8.3.0",
    "eslint-plugin-prettier": "^5.2.2",
    "prettier": "^3.0.3"
  }

  // .eslintrc.js
  extends: [ 'eslint:recommended' ],  // Added along with other existing value
  plugins: ['react-hooks'],           // Added along with other existing value
</code></pre>
</li>
</ul>
</li>
<li>
<p><strong>Replaced <code>mime-types</code> with <code>mime</code></strong>:</p>
<ul>
<li>The <code>mime-types</code> is not getting updates, ref: <a href="https://github.com/jshttp/mime-types/issues/50#issuecomment-442916069">Mime types docs</a>, as it throwing error due to one of core module not existing and it also saves to add @types/mime-types explicitly.</li>
<li>Reference: <a href="https://github.com/jshttp/mime-types/issues/50#issuecomment-442916069">Mime-Types Issue</a>.</li>
</ul>
</li>
<li>
<p><strong>Optional Chaining in Environment Variables</strong>:</p>
<ul>
<li>Fixed <code>process?.env?.REACT_APP_MA_BASE_DEAL</code> to <code>process.env.REACT_APP_MA_BASE_DEAL</code>, we should avoid optional channing while using environment variable.</li>
<li>Reference: <a href="https://github.com/facebook/create-react-app/issues/12374">Create React App Issue</a>.</li>
</ul>
</li>
<li>
<p><strong>Enforced Specific Package Version</strong>:</p>
<ul>
<li>To resolve white screen issue, Added <code>overrides</code> in <code>package.json</code> for <code>react-error-overlay</code>, some dependent packages using different version so here we need to enforce while writing in package.json:
<pre><code class="language-json">"overrides": {
  "react-error-overlay": "6.0.9"
}
</code></pre>
</li>
</ul>
<p>if you're using <code>yarn</code>, need to pass same object with <code>"resolutions"</code> instead of <code>"overrides"</code>.</p>
</li>
<li>
<p><strong>React-Refresh Issue</strong>:</p>
<ul>
<li>
<p>Added <code>FAST_REFRESH=false</code> in <code>.env</code> to resolve intermittent blank-page issue.</p>
<pre><code>> Uncaught RangeError: Maximum call stack size      at react-refresh-runtime.development.js
 exeeded.
    at WeakMap.get(&#x3C;anonymous>)
    at computeFullKey (react-refresh-devel...js)
    at ...
</code></pre>
<p></p>
</li>
</ul>
</li>
<li>
<p><strong>Engine Specification</strong>:</p>
<ul>
<li>Added the following in <code>package.json</code>:
<pre><code class="language-json">"engine": {
  "node": ">=20.9.0"
}
</code></pre>
</li>
</ul>
</li>
<li>
<p><strong>Webpack Deprecation Warning</strong>:</p>
<ul>
<li>
<p>Warning:</p>
<pre><code>  [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DecprecationWarning: 'OnAfterSetupMiddleWare', 'onBeforeSetupMiddleware',... Please use the 'setupMiddlewares' option...
</code></pre>
<p>As of now fixing this issue. the two solutions found in internet, both we cannot apply in current project as it not recommended way, one is talking about file changes inside node_modules as below:</p>
<pre><code class="language-js">// react-scripts\config\webpackDevServer.config.js
setupMiddlewares: (middlewares, devServer) => {
  if (!devServer) {
    throw new Error('webpack-dev-server is not defined')
  }
  if (fs.existsSync(paths.proxySetup)) {
    require(paths.proxySetup)(devServer.app)
  }
  middlewares.push(
    evalSourceMapMiddleware(devServer),
    redirectServedPath(paths.publicUrlOrPath),
    noopServiceWorkerMiddleware(paths.publicUrlOrPath)
  )
return middlewares;
}
</code></pre>
<p>Second solution talks about ejecting packages. one additional way we can fix above warning is after modify webpack configs and can also add polyfills, using <code>react-app-rewired</code> or <code>craco</code> both works fine we can include <code>node-polyfill-webpack-plugin</code> we can refer below links in future if we need it. Not using it as of now.</p>
<ul>
<li><a href="https://thecodersblog.com/polyfill-node-core-modules-webpack-5">Polyfill Node Modules</a>,</li>
<li><a href="https://stackoverflow.com/a/74984204/7242575">StackOverflow Reference 1</a></li>
<li><a href="https://stackoverflow.com/a/71280203/7242575">StackOverflow Reference 2</a></li>
<li><a href="https://stackoverflow.com/a/70485253/7242575">StackOverflow Reference 3</a>.</li>
</ul>
<p></p>
</li>
</ul>
</li>
</ol>
]]></content:encoded>
            <author>bhar4t@outlook.com (Bharat Sahu)</author>
            <enclosure url="https://webkoof.in/img/node-upgrade-20.webp" length="0" type="image/webp"/>
        </item>
        <item>
            <title><![CDATA[How to publish a React component to npm?]]></title>
            <link>https://webkoof.in/articles/Publish-a-React-component-to-npm</link>
            <guid isPermaLink="false">https://webkoof.in/articles/Publish-a-React-component-to-npm</guid>
            <pubDate>Fri, 06 Aug 2021 00:00:00 GMT</pubDate>
            <description><![CDATA[Learn how to publish your own React component to npm in a few simple steps. This guide covers everything from setting up your project to publishing your component for others to use.]]></description>
            <content:encoded><![CDATA[<h2>Steps to Publish Your React Component</h2>
<h3>1. Create a React Application</h3>
<p>Use Create React App to set up your project:</p>
<pre><code class="language-bash">npx create-react-app your-component-name
</code></pre>
<h3>2. Add Development Dependencies</h3>
<p>Install Babel CLI and the React preset:</p>
<pre><code class="language-bash">npm install --save-dev @babel/cli @babel/preset-react
</code></pre>
<p>Or, if using yarn:</p>
<pre><code class="language-bash">yarn add --dev @babel/cli @babel/preset-react
</code></pre>
<h3>3. Configure Babel</h3>
<p>Add the Babel React preset to your <code>package.json</code>:</p>
<pre><code class="language-json">"babel": {
  "presets": [
    "@babel/preset-react"
  ]
}
</code></pre>
<h3>4. Set Package Visibility</h3>
<p>Change the <code>private</code> field in <code>package.json</code> to <code>false</code>:</p>
<pre><code class="language-json">"private": false
</code></pre>
<h3>5. Add Build Script</h3>
<p>Include a script to transpile your component and copy it to the <code>dist</code> directory. Add the following to the <code>scripts</code> section of your <code>package.json</code>:</p>
<p>For Windows:</p>
<pre><code class="language-json">"publish:npm": "rmdir /s /q dist &#x26;&#x26; mkdir dist &#x26;&#x26; babel .\src\component -d dist --copy-files"
</code></pre>
<p>For Linux:</p>
<pre><code class="language-json">"publish:npm": "rm -rf dist &#x26;&#x26; mkdir dist &#x26;&#x26; babel src/component -d dist --copy-files"
</code></pre>
<h3>6. Create Your Component</h3>
<p>Inside the <code>src</code> directory, create a folder named <code>component</code> (or any name you prefer) and add your component file, e.g., <code>index.js</code>:</p>
<pre><code class="language-jsx">import React from 'react';

function ReusableComponent() {
  return (
    &#x3C;div>
      Hello, World!
    &#x3C;/div>
  );
}

export default ReusableComponent;
</code></pre>
<h3>7. Specify the Entry Point</h3>
<p>In <code>package.json</code>, set the <code>main</code> field to point to your compiled component:</p>
<pre><code class="language-json">"main": "./dist/index.js"
</code></pre>
<h3>8. Define Peer Dependencies</h3>
<p>Move React-related dependencies to <code>peerDependencies</code> in <code>package.json</code> to avoid duplication in projects that install your component:</p>
<pre><code class="language-json">"peerDependencies": {
  "react": "^17.0.2",
  "react-dom": "^17.0.2"
}
</code></pre>
<h3>9. Build Your Component</h3>
<p>Run the build script to generate the <code>dist</code> directory:</p>
<pre><code class="language-bash">npm run publish:npm
</code></pre>
<p>Or, if using yarn:</p>
<pre><code class="language-bash">yarn publish:npm
</code></pre>
<h3>10. Publish to npm</h3>
<p>Ensure you're logged in to npm and publish your package:</p>
<pre><code class="language-bash">npm login
npm publish
</code></pre>
<p>Remember to update the version number in <code>package.json</code> before each publish.</p>
<hr>
<p>By following these steps, you can share your React components via npm for reuse in other projects.</p>
<p><a href="https://www.npmjs.com/package/reuse-react-component">Published NPM React Component</a></p>
]]></content:encoded>
            <author>bhar4t@outlook.com (Bharat Sahu)</author>
            <enclosure url="https://webkoof.in/img/npm.webp" length="0" type="image/webp"/>
        </item>
        <item>
            <title><![CDATA[What is Temporal Dead Zone in JavaScript?]]></title>
            <link>https://webkoof.in/articles/What-is-Temporal-Dead-Zone-in-JavaScript</link>
            <guid isPermaLink="false">https://webkoof.in/articles/What-is-Temporal-Dead-Zone-in-JavaScript</guid>
            <pubDate>Sat, 01 May 2021 00:00:00 GMT</pubDate>
            <description><![CDATA[The Temporal Dead Zone (TDZ) is a specific time between whenever we declare any variable using `let` keyword and initializing declared variable a value, the time span between these two events known to be as temporal dead zone.]]></description>
            <content:encoded><![CDATA[<p>Before starting this blog, I would recommend to read blog on <a href="https://webkoof.in/articles/hoisting-in-JavaScript">Hoisting in JavaScript</a>.</p>
<p>The Temporal Dead Zone (TDZ) is a specific time between whenever we declare any variable using <code>let</code> keyword and initializing declared variable a value, the time span between these two events known to be as temporal dead zone, whenever we try to use variable in between temporal dead zone state, we get <code>Reference Error</code> because it will be always unreachable for the particular time being till it gets initialized.</p>
<pre><code class="language-js">console.log(num);

let num = 10;
</code></pre>
<p>In memory creation phase of the <code>num</code> will be hoisted inside the special memory area of Javascript engine, and in the second phase or code execution phase if engine try to execute above code value of num will be unreachable because the initialization happens in second line. so the line number 1st will give us an <code>Reference Error</code>.</p>
<h2>Why TDZ not with <code>const</code> and <code>var</code>?</h2>
<p>Because of hoisting we can access any variable created using <code>var</code> even before it gets declared, and we get an special value as <code>undefined</code> because it attached to global object.</p>
<p>It doesn't mean variable created with <code>const</code> and <code>let</code> are not hoisted but in the case of <code>const</code> the initialization must be in the same line while declaring the variable.</p>
<h2>References:</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let</a></li>
</ul>
]]></content:encoded>
            <author>bhar4t@outlook.com (Bharat Sahu)</author>
            <enclosure url="https://webkoof.in/img/tdz.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[What is prototype in JavaScript?]]></title>
            <link>https://webkoof.in/articles/What-is-prototype-in-JavaScript</link>
            <guid isPermaLink="false">https://webkoof.in/articles/What-is-prototype-in-JavaScript</guid>
            <pubDate>Thu, 22 Apr 2021 00:00:00 GMT</pubDate>
            <description><![CDATA[We often heard JavaScript is prototype-based language but what is prototype in JavaScript? Why it is known to be as prototype-based language?]]></description>
            <content:encoded><![CDATA[<p>The entire inheritance concept in JavaScript is based on prototype, prototype inheritence is whenever we create any <code>object</code> or <code>function</code> in JavaScript it automatically inherit properties and methods from certain template object or prototype object.</p>
<p>Here you can understand better, there are number of prototype objects in JavaScript (eg: <code>Array.prototype</code>, <code>Function.prototype</code>, <code>Object.prototype</code> etc.). So whenever we create any <code>array</code>, <code>function</code> or <code>object</code> JavaScript engine internally attaches the prototype template's properties and methods into your newly created object. that is why we can access in-built functionality of certain objects like when we create any <code>array</code> we get method like <code>push</code>, <code>map</code>, similarly for functions we get <a href="https://webkoof.in/articles/bind()-call()-and-apply()-in-JavaScript"><code>call</code>, <code>apply</code> and <code>bind</code></a> and for objects we get <code>toString</code>, <code>hasOwnProperty</code> and etc.</p>
<p>In JavaScript everything is object, and every object has a property as <code>__proto__</code>, in this property you can see all properties and methods that acquired from another object or template object.</p>
<pre><code class="language-js">let object = {};

console.log(object.__proto__);

// constructor: ƒ Object()
// hasOwnProperty: ƒ hasOwnProperty()
// isPrototypeOf: ƒ isPrototypeOf()
// propertyIsEnumerable: ƒ propertyIsEnumerable()
// toLocaleString: ƒ toLocaleString()
// toString: ƒ toString()
// valueOf: ƒ valueOf()
// __defineGetter__: ƒ __defineGetter__()
// __defineSetter__: ƒ __defineSetter__()
// __lookupGetter__: ƒ __lookupGetter__()
// __lookupSetter__: ƒ __lookupSetter__()
// get __proto__: ƒ __proto__()
// set __proto__: ƒ __proto__()
</code></pre>
<p>The output you are seeing here will be the same as <code>Object.prototype</code>.</p>
<h2>What is <code>__proto__</code>?</h2>
<p>The <code>__proto__</code> attribute used to assign the properties and methods from prototype template. Whenver we want to inherit propeties and methods from prototype template we can just assign it into child's <code>__proto__</code> attribute, You can directly understand this field by below example:</p>
<pre><code class="language-js">const human = {
  teeth: 32,
};

const john = {
  __proto__: human,
  leg: 2,
};

console.log(john.teeth);
// 32
</code></pre>
<p>So, here in the above example we've created a <code>human</code> object and it have a field as <code>teeth</code> with value <code>32</code>, and we've also created another object as <code>john</code>, and it have 2 fields first is field <code>leg</code> and it have value as <code>2</code>, but here we want to inherit properties from <code>human</code> object in <code>john</code> object, so we've just assigned <code>human</code> into <code>john</code>'s <code>__proto__</code>.</p>
<p>Let's see how it printing the value.. whenever we access <code>john.teeth</code>, javascript engine will try to find the <code>teeth</code> field inside <code>john</code> object and when it didn't find, it will go to <code>john</code>'s <code>__proto__</code> and if <code>teeth</code> available, it will print the value.</p>
<p>So whenver the finding goes on various level, known to be as Prototypical Chain.</p>
<p>We've already seen the example, how to use the <code>prototype</code> property, how can we make available other properties and methods for newly created objects in the article <a href="https://webkoof.in/articles/Polyfill-for-bind()-step-by-step">Polyfill for bind()-step-by-step</a>.</p>
<h2>References:</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes</a></li>
</ul>
]]></content:encoded>
            <author>bhar4t@outlook.com (Bharat Sahu)</author>
            <enclosure url="https://webkoof.in/img/prototype-javascript.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Hoisting in JavaScript]]></title>
            <link>https://webkoof.in/articles/hoisting-in-JavaScript</link>
            <guid isPermaLink="false">https://webkoof.in/articles/hoisting-in-JavaScript</guid>
            <pubDate>Mon, 05 Apr 2021 00:00:00 GMT</pubDate>
            <description><![CDATA[When you use variables and functions before declaration without getting any error known to be as `Hoisting`.]]></description>
            <content:encoded><![CDATA[<p>Can you call any function before declaration? or can you use any variable before declaration?</p>
<p>If you coming from another programming language background like C, C++, or Java you will probably say <em>No</em>, but in the case of JavaScript, you can definitely access those variables and functions because of <code>Hoisting</code>.</p>
<p>When you use variables and functions before declaration without getting any error known to be as <code>Hoisting</code>.
See below:</p>
<pre><code class="language-js">    greet() // Hello World!

    function greet() {
        console.log('Hello, World!')
    }
</code></pre>
<p>Similarly for variables</p>
<pre><code class="language-js">    console.log(name) // undefined

    var name = 'John Doe'
</code></pre>
<p>Or</p>
<pre><code class="language-js">    name = 'John Doe';
    console.log(name); //John Doe
    var name;
</code></pre>
<p>Yes! In the case of functions, it executing what should be executed, but for variables, it printing a special value <code>undefined</code>.</p>
<p>Maybe you're thinking it will show any variable which is written or not written in the current script but when you see below, We're trying to use a variable that is nowhere defined in our script, it's actually throwing an error:</p>
<pre><code class="language-js">    console.log(noWhereDefinedVar) // ReferenceError: noWhereDefinedVar is not defined
</code></pre>
<p>Actually, it's happening because of JavaScript's execution behavior, whenever we start the execution of the current script or current function is executed in two phases first is the <em>Memory Creation Phase</em>, and another one is the <em>Code Execution Phase</em>.</p>
<p>So, in the <em>Memory Creation Phase</em> means before execution of code, memory allocated for all the variables and for the functions. The variables get special value i.e. <code>undefined</code> and functions literally copied in its allocated memory space and whenever <em>Memory Creation Phase</em> completed then only execution starts.</p>
<h2>What happens in the case of <code>let</code> and <code>const</code>?</h2>
<p>The <code>let</code> and <code>const</code> also hoisted, but it behaves differently, we cannot use variable declared with <code>let</code> and <code>const</code> before initialization, cause <code>let</code> or <code>const</code> have a block level scope it is created in special memory space, example with let:</p>
<pre><code class="language-js">    num = 1; // initialization.

    let num;
    // Throws ReferenceError: Cannot access 'a' before initialization
</code></pre>
<p>Example with const:</p>
<pre><code class="language-js">    NUM = 1; // initialization.

    const NUM;
    // Throws SyntaxError: Missing initializer in const declaration
</code></pre>
<p>Best Practices:</p>
<ul>
<li>Use <code>let</code>/<code>const</code> over <code>var</code>. try to use these in priority is like <code>const</code> > <code>let</code> > <code>var</code>.</li>
<li>Declare variable always on the top of the script/function, Try to avoid the use of variables before initialization.</li>
</ul>
<p>Practice with the below code and answer me what will be the answer:</p>
<pre><code class="language-js">    sayHello()

    var sayHello = function greet() { 
        console.log('Hello, World!')
    }
</code></pre>
<h2>References:</h2>
<ul>
<li>https://developer.mozilla.org/en-US/docs/Glossary/Hoisting</li>
<li>https://en.wikipedia.org/wiki/JavaScript_syntax</li>
</ul>
]]></content:encoded>
            <author>bhar4t@outlook.com (Bharat Sahu)</author>
            <enclosure url="https://webkoof.in/img/hoisting.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Function currying in JavaScript]]></title>
            <link>https://webkoof.in/articles/Function-currying-in-JavaScript</link>
            <guid isPermaLink="false">https://webkoof.in/articles/Function-currying-in-JavaScript</guid>
            <pubDate>Mon, 29 Mar 2021 00:00:00 GMT</pubDate>
            <description><![CDATA[In Mathematics and Computer Science, currying is the technique of converting a function that takes multiple arguements into a sequence of functions that each take a single argument.]]></description>
            <content:encoded><![CDATA[<p>In Mathematics and Computer Science, currying is the technique of converting a function that takes multiple arguements into a sequence of functions that each take a single argument.</p>
<p>For example, Given a function with 3 parameters, The curried version will take one argument and returns a function that takes the next argument, which return a function that takes the third argument. The last function returns the result of applying function to all of the arguments. we can do it for more or fewer parameters.</p>
<p>To see the benefit of currying we are going to write an example that is useful for logging, for now we're going to only <code>console.log</code>, you can further implement it for actual loggings like in server, or in any log file.</p>
<pre><code class="language-js">    function log (date) {
        return function (mode) {
            return function (message) {
                console.log(`[${date.getHours()}:${date.getMinutes()}] [${mode}] ${message}`)
            }
        }
    }
</code></pre>
<p>We can make it call like this</p>
<pre><code class="language-js">    log(new Date())("DEBUG")("some debug")
    // [HH:mm] [DEBUG] some debug
</code></pre>
<p><code>logNow()</code> will be the partial of log with fixed first argument</p>
<pre><code class="language-js">    let logNow = log(new Date())
</code></pre>
<p>We can use it as</p>
<pre><code class="language-js">    logNow("INFO")("message")
    // [HH:mm] [INFO] message
</code></pre>
<p>Or</p>
<pre><code class="language-js">    let debugNow = logNow("DEBUG")

    debugNow("message")
    // [HH:mm] [DEBUG] message
</code></pre>
<p>See, we can easily generate a partial function for today's log when called with one argument (like <code>log(date)</code>) or two arguments (like <code>logNow(mode)(message)</code>).</p>
<p>The <code>logNow</code> function takes one arguement, and then returns a partial application of itself with <code>date</code> fixed in the <code>Closure scope</code>.</p>
<p>A Closure is a function bundled with its lexical scope. The Closures created at runtime while function creation.</p>
<p>Let's see another simple and beautiful example of currying using <code>bind()</code> method. we're going define a method which will add two numbers.</p>
<pre><code class="language-js">    function add (a, b) {
        console.log(a + b)
    }
</code></pre>
<p>Now we're going to create an increment method by using <code>bind()</code>, means any number we pass and it will increment it by 1.</p>
<pre><code class="language-js">    let increment = add.bind(this, 1)
    increment(5)
    // 6
</code></pre>
<p>See we didn’t lose anything after currying: <code>add</code> is still callable normally.</p>
<p>Similarly we can specialize number of method using currying, The method below will increment any number by 10.</p>
<pre><code class="language-js">    add.bind(this, 10)(5)
    // 15
</code></pre>
<h2>References:</h2>
<ul>
<li>https://en.wikipedia.org/wiki/Currying</li>
<li>https://javascript.info/currying-partials</li>
<li>https://medium.com/javascript-scene/curry-and-function-composition-2c208d774983</li>
</ul>
]]></content:encoded>
            <author>bhar4t@outlook.com (Bharat Sahu)</author>
            <enclosure url="https://webkoof.in/img/currying.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Polyfill for bind(), step-by-step]]></title>
            <link>https://webkoof.in/articles/Polyfill-for-bind()-step-by-step</link>
            <guid isPermaLink="false">https://webkoof.in/articles/Polyfill-for-bind()-step-by-step</guid>
            <pubDate>Sun, 28 Mar 2021 00:00:00 GMT</pubDate>
            <description><![CDATA[Polyfill is nothing but support to older browsers which doesn't have new methods. In this tutorial, you'll learn how to write the Polyfill for the `bind()` method in step by step.]]></description>
            <content:encoded><![CDATA[<p>Polyfill is nothing but support to older browsers which doesn't have new methods. In this tutorial, you'll learn how to write the Polyfill for the <code>bind()</code> method in step by step.</p>
<p>first of all, you need to see the <code>bind()</code> method, and how it works. look at the snippet below:</p>
<pre><code class="language-js">    let name = {
        firstName: "John",
        lastName: "Doe"
    }

    function printFullName () {
        console.log(this.firstName + ' ' + this.lastName)
    }

    let printName = printFullName.bind(name)
    printName()
    // John Doe
</code></pre>
<p>If you need to create your own <code>bind()</code> method, you've to breakdown the above-mentioned snippet.</p>
<p>First, you need to make it available for all the method so we're going to take help from the <code>prototype</code> of <code>Function</code>, The snippet will be like:</p>
<pre><code class="language-js">    Function.prototype.polyfill_bind = function () {
        //...
    }
</code></pre>
<p>The polyfill_bind() is a user-defined function you can name anything you want and, now it will be available for any function you define in your code like other functions toString(), toLocaleString(), etc.</p>
<p>And now we're able to make a call similar to the original <code>bind()</code> method:</p>
<pre><code class="language-js">    printFullName.polyfill_bind(name)
</code></pre>
<p>Wait it is not completed yet! need to implement logic so it can work exactly like the <code>bind()</code> method. As we know the <code>bind()</code> method returns a method after creating a new copy of the original method so we make a function call later so we need to return a function whenever we make a call to our <code>polyfill_bind()</code>.</p>
<pre><code class="language-js">    Function.prototype.polyfill_bind = function () {
        return function () {
            // ...
        }
    }

    let showName = printFullName.polyfill_bind(name);
    showName();
</code></pre>
<p>We have created the basic skeleton for our <code>polyfill_bind()</code> but, still we haven't implemented actual logic on how <code>bind()</code> works. So first we need to manage the function call we're trying to bind with the particular object.</p>
<pre><code class="language-js">    Function.prototype.polyfill_bind = function () {
        let context = this;
        return function () {
            context.call(/* Need to pass arguments */)
        }
    }
</code></pre>
<p>As we know, the first argument for the <code>bind()</code> method is always an object for which the callee bind to be and it can be any number of argument so we can take it as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameter  or <code>varargs</code></a>, then the above can be written as:</p>
<pre><code class="language-js">    Function.prototype.polyfill_bind = function (...args) {
        let context = this;
        return function () {
            context.call(args[0])
        }
    }
</code></pre>
<p>We're almost there, we also need to take care of other arguments that can be passed with our <code>polyfill_bind()</code> and the method which copied using the <code>polyfill_bind()</code> method, and it can be any number of arguments so I'm converting it to <code>apply()</code> cause it is similar to <code>call() </code> method but it takes an array as in argument:</p>
<pre><code class="language-js">    Function.prototype.polyfill_bind = function (...args) {
        let context = this;
        let params = args.slice(1)
        return function (...args2) {
            context.apply(args[0], [...params, ...args2] )
        }
    }
</code></pre>
<p>Don't confuse here, we're using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">Spread operator or the three-dot notation</a> to concat two arrays here. The first array is <code>param</code>, we sliced out the first element from it, and the second array is <code>args2</code>, which we're taking as the argument from the method, i.e. <code>showName(value1, value2, …valueN)</code>.</p>
<p>Or we can make it with <code>call()</code> method version by replacing line <code>context.apply(args[0], [...params, ...args2] )</code> with:</p>
<pre><code class="language-js">    context.call(args[0], ...params, ...args2)
</code></pre>
<p>So the full implementation of our polyfill for <code>bind()</code> is which works exactly like the <code>bind()</code> method:</p>
<pre><code class="language-js">    let name = {
        firstName: "John",
        lastName: "Doe"
    }

    function printFullName (city, country) {
        console.log(this.firstName + ' ' + this.lastName + ' from ' + city + ', ' + country)
    }

    Function.prototype.polyfill_bind = function (...args) {
        let context = this;
        let params = args.slice(1)
        return function (...args2) {
            context.apply(args[0], [...params, ...args2] )
            // Or
            // context.call(args[0], ...params, ...args2)
        }
    }

    let showName = printFullName.polyfill_bind(name, 'Jabari village')
    showName('Wakanda');

    // Output: John Doe from Jabari village, Wakanda
</code></pre>
<h2>References:</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">Function.prototype.apply()</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind">Function.prototype.bind()</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">Function.prototype.call()</a></li>
</ul>
<p><a href="https://bhar4t.medium.com/polyfill-for-bind-step-by-step-c0f19a5dbd17">Read on Medium</a></p>
]]></content:encoded>
            <author>bhar4t@outlook.com (Bharat Sahu)</author>
            <enclosure url="https://webkoof.in/img/implement-bind-polyfill.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[bind(), call() and apply() in JavaScript]]></title>
            <link>https://webkoof.in/articles/bind()-call()-and-apply()-in-JavaScript</link>
            <guid isPermaLink="false">https://webkoof.in/articles/bind()-call()-and-apply()-in-JavaScript</guid>
            <pubDate>Sat, 27 Mar 2021 00:00:00 GMT</pubDate>
            <description><![CDATA[The `this` keyword in JavaScript is not like other programming language's `this`, it behaves differently in different scenario.]]></description>
            <content:encoded><![CDATA[<p>The <code>this</code> keyword in JavaScript is not like other programming language's <code>this</code>, it behaves differently in different scenario.</p>
<p>Let's see this in example:</p>
<pre><code class="language-js">    const name = {
        firstName: 'John',
        lastName: 'Doe',
        showFullName: function() {
                console.log(this.firstName + ' ' + this.lastName);
        }
    };
</code></pre>
<p>Try to execute <code>showFullName()</code> method</p>
<pre><code class="language-js">    name.showFullName()
</code></pre>
<p>The outpout will be</p>
<pre><code class="language-js">    John Doe
</code></pre>
<p>Calling the showFullName() method with the <code>name</code> object, so the this keyword refers to the <code>name</code> object.</p>
<p>Let’s assign the name object's <code>showFullName()</code> method to any identifier to use it without the <code>name</code> object.</p>
<pre><code class="language-js">    const printName = name.showFullName
    printName()
</code></pre>
<p>So if we execute the above-mentioned code, the output:</p>
<pre><code class="language-js">    undefined undefined
</code></pre>
<p>Shocked! Why this happening?</p>
<p>Here, we are storing a reference of <code>name.showFullName()</code> to <code>printName</code> variable. After that, we are calling it without an object reference, so this will now refer to the window (global) object or undefined (in strict mode).</p>
<p>Similarly, other examples are:</p>
<pre><code class="language-js">    function DemoFunction() {
        console.log(this);
    }
    // Constructor invocation
    new DemoFunction(); // logs an instance of DemoFunction
</code></pre>
<pre><code class="language-js">    const demoObject = {
        demoMethod() {
            console.log(this);
        }
    };
    // Method invocation
    demoObject.demoMethod(); // logs demoObject
</code></pre>
<pre><code class="language-js">    function demoFunction() {
        console.log(this);
    }
    // Simple invocation
    demoFunction(); // logs global object (window)
</code></pre>
<p>So, The apply(), bind() and, call() is saviour here. Here the value of <code>this</code> equals to the first argument.</p>
<p>Now we define another name object as <code>name2</code>:</p>
<pre><code class="language-js">    let name2 = {
        firstName: "Bharat",
        lastName: "Sahu"
    }
</code></pre>
<p>and define a separate <code>showFullName()</code> method:</p>
<pre><code class="language-js">    let showFullName = function (city, state) {
        console.log(this.firstName + " " + this.lastName + " from " + city + ", " + state);
    }
</code></pre>
<h2>call()</h2>
<p>The <code>call()</code> method calls a function with a given this value and arguments provided individually.</p>
<p>and we make call with call()  method:</p>
<pre><code class="language-js">    showFullName.call(name2, 'Raipur', 'Chhattisgarh');
    // output: Bharat Sahu from Raipur, Chhattisgarh
</code></pre>
<h2>apply()</h2>
<p>similar to <code>call()</code>, but expects an array of all of our parameters.</p>
<pre><code class="language-js">    showFullName.apply(name2, ['Raipur', 'Chhattisgarh']);
    // output: Bharat Sahu from Raipur, Chhattisgarh
</code></pre>
<h2>bind()</h2>
<p>The <code>bind()</code> method creates a new function that, when called, has its this keyword set to the provided value.</p>
<pre><code class="language-js">    // bind, when we need to call method later
    const showMyName = showFullName.bind(name2, 'Raipur', 'Chhattisgarh');
    showMyName();
    // output: Bharat Sahu from Raipur, Chhattisgarh
</code></pre>
<p>The full code snippets will be:</p>
<pre><code class="language-js">    let name2 = {
        firstName: "Bharat",
        lastName: "Sahu"
    }

    let showFullName = function (city, state) {
        console.log(this.firstName + " " + this.lastName + " from " + city + ", " + state);
    }

    showFullName.call(name2, 'Raipur', 'Chhattisgarh');
    // output: Bharat Sahu from Raipur, Chhattisgarh

    showFullName.apply(name2, ['Raipur', 'Chhattisgarh']);
    // output: Bharat Sahu from Raipur, Chhattisgarh

    const showMyName = showFullName.bind(name2, 'Raipur', 'Chhattisgarh');
    showMyName();
    // output: Bharat Sahu from Raipur, Chhattisgarh
</code></pre>
<h2>References:</h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">Function.prototype.apply()</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind">Function.prototype.bind()</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">Function.prototype.call()</a></li>
</ul>
]]></content:encoded>
            <author>bhar4t@outlook.com (Bharat Sahu)</author>
            <enclosure url="https://webkoof.in/img/apply-bind-call.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Cordova with Firebase Phone Authentication without Captcha]]></title>
            <link>https://webkoof.in/articles/Cordova-with-Firebase-Phone-Authentication-without-Captcha-and-reCaptcha</link>
            <guid isPermaLink="false">https://webkoof.in/articles/Cordova-with-Firebase-Phone-Authentication-without-Captcha-and-reCaptcha</guid>
            <pubDate>Fri, 10 Apr 2020 00:00:00 GMT</pubDate>
            <description><![CDATA[We’re going to use Firebase Phone Authentication using firebase-js-sdk without Captcha with ReactJS application in a simple way. This article is for people who has basic knowledge of Cordova and Firebase phone authentication.]]></description>
            <content:encoded><![CDATA[<p>We’re going to use Firebase Phone Authentication using firebase-js-sdk without Captcha with ReactJS application in a simple way. This article is for people who has basic knowledge of Cordova and Firebase phone authentication.</p>
<p>If you implement Firebase phone authentication using Cordova plugin, it must be capable to provide all the Firebase services otherwise, your Cordova application cannot perform CRUD operations with <code>firebase-js-sdk</code> where authentication required.</p>
<p>Or, if you want to implement Firebase phone authentication with firebase-js-sdk, you have to configure things related to Captcha/reCaptcha. You can see <a href="https://firebase.google.com/docs/auth/web/phone-auth">here</a> in the official document.</p>
<p>Here I’ve found solution by combining both the dependencies i.e. firebase-js-sdk and a Cordova plugin so we don't need to configure all Captha related tasks.</p>
<p>Step I: Initially we have to create an Android project in Firebase console. where I have to register my new Android application <strong>name</strong> and <strong>package name</strong> in Firebase console. cause you won’t have an option for the Cordova application.</p>
<p>You’ll see the third option while registering the app as <strong>Debug signing certificate SHA-1</strong>. It seems optional but because we’re creating authentication based application I’ll recommend you generate those certificates. <a href="https://developers.google.com/android/guides/client-auth">You can generate debug certificates by following it</a> or by the following command default password is <code>android</code></p>
<p>Ubuntu</p>
<pre><code>    keytool -list -v -alias keystore -keystore ~/.android/debug.keystore
</code></pre>
<p>Windows</p>
<pre><code>    keytool -list -v -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore
</code></pre>
<p>Generated certificate output will be like below:</p>
<pre><code>Certificate fingerprint: SHA1: DA:39:A3:EE:5E:6B:4B:0D:32:55:BF:EF:95:60:18:90:AF:D8:07:09
</code></pre>
<p>Just copy the <strong>SHA1</strong> fingerprint and paste in the third input field <strong>Debug signing certificate SHA-1</strong>. after then click to <strong>Register App.</strong></p>
<p>Step II: The below screen will appear after click on the <strong>Register App</strong> button.</p>
<p>Click on the <strong>Download google-service.json,</strong> you’ll have a JSON file, place it on the root of your project. and, remember you need to specify in <code>config.xml</code> for <code>google-service.json</code> so, Cordova will place the copied file inside <em>platforms/android/app</em> directory while generating the app.</p>
<pre><code class="language-xml">&#x3C;platform name="android">
    &#x3C;resource-file
      src="google-services.json"
      target="app/google-services.json"
    />
&#x3C;/platform>
</code></pre>
<p>after this click on Next, Next… Finally, you’ve set up an Android project in Firebase.</p>
<p>Step III: Now, you have to enable the Phone Authentication for your newly registered Android application.</p>
<ol>
<li>Select <strong>Authentication</strong> from <strong>Develop</strong> option.</li>
<li>Choose <strong>Sign-in method</strong></li>
<li>Choose <strong>Phone</strong></li>
<li>Just <strong>Enable</strong> it from the right upper toggle button</li>
<li>By clicking on <strong>Save</strong>, we’ve finished the configuration here.</li>
</ol>
<hr>
<p>Now we’ve to look upon our local project, You will see the major role of two dependencies. because we’re not going to use Captcha/reCaptcha I’ll use a Cordova plugin for generating verification id for phone numbers. and we’re going to verify that verification id and OTP by using <code>firebase-js-sdk</code>. Add these dependencies by below commands:</p>
<ol>
<li>Cordova plugin <a href="https://github.com/chemerisuk/cordova-plugin-firebase-authentication">cordova-plugin-firebase-authentication</a></li>
</ol>
<pre><code>cordova plugin add cordova-plugin-firebase-authentication --save
</code></pre>
<ol start="2">
<li>Add <a href="https://www.npmjs.com/package/firebase">firebase-js-sdk</a> in your project, using npm:</li>
</ol>
<pre><code>    npm i firebase
</code></pre>
<p>Or using yarn</p>
<pre><code>    yarn add firebase
</code></pre>
<ol start="3">
<li>Configure your <code>firebase-js-sdk</code> to already created projects on Firebase console. you need to create a file as I’ve created in <code>src/store.js</code> and use this boilerplate code for configuration.</li>
</ol>
<pre><code class="language-js">import firebase from "firebase";
import "firebase/firestore";
import "firebase/auth";

const config = firebase.initializeApp({
  apiKey: '&#x3C;your-api-key>',
  authDomain: '&#x3C;your-auth-domain>',
  databaseURL: '&#x3C;your-database-url>',
  projectId: '&#x3C;your-cloud-firestore-project>',
  storageBucket: '&#x3C;your-storage-bucket>',
  messagingSenderId: '&#x3C;your-sender-id>'
  appId: '&#x3C;key>:&#x3C;key>:&#x3C;android>:&#x3C;your-sender-id>',
});

const auth = firebase.auth();
const db = config.firestore();

export { auth, firebase };
</code></pre>
<p>You can get configuration details in <code>google-service.json</code> for firebase app initialization or if you feel the hassle to get those keys/configurations detail in one place, Add a web app in the same project of Firebase console where we added the Android app before. you’ll have exactly the same configuration detail as mentioned above in <strong>Project Settings > Web Apps > Firebase SDK snippet</strong> copy and paste the config in your project.</p>
<p>Here I have exported instances <code>auth,</code> <code>firebase</code> now I can use it wherever I want.</p>
<p>Its time to design the login page, Here we’ll talk about code snippet, not about UI but in the <a href="https://github.com/bhar4t/auth-cordova"><strong>Github repository</strong></a><strong>,</strong> you’ll get the full code.</p>
<ol start="4">
<li>I have created a <code>Login.js</code> page, where I have to register a listener method for an authenticated user. You can register your listener in React’s lifecycle method <a href="https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops">static getDerivedStateFromProps</a> and, if you’re using React Hooks you can register it in <a href="https://reactjs.org/docs/hooks-reference.html#useeffect">useEffect</a>.</li>
</ol>
<pre><code class="language-js">import { auth, firebase } from "./store";
</code></pre>
<p>Whenever a user logged in or log out listener method will be invoked automatically, I have registered listener method from <code>firebase-js-sdk</code> of <code>auth</code>. You’ll see a listener method in added Cordova plugin too but we’re not going to use it because we have decided to work with <code>firebase-js-sdk</code>.</p>
<pre><code class="language-js">auth.onAuthStateChanged((authUser) => {
  if (authUser) {
    // Pass authUser
  } else {
    // Handle null
  }
});
</code></pre>
<p>Create a function, that will starts the phone number verification process for the given phone number. for this use the Cordova plugin method inside <code>verifyPhoneNumber</code> which takes two parameters first phone number along with country code and second is <code>timeout</code> [milliseconds] is the maximum amount of time you are willing to wait for SMS auto-retrieval to be completed by the library. The maximum allowed value is 2 minutes. Use 0 to disable SMS-auto-retrieval. If you specify a positive value less than 30 seconds, the library will default to 30 seconds.</p>
<pre><code class="language-js">cordova.plugins.firebase.auth
  .verifyPhoneNumber("+91" + phoneNumber, 0)
  .then((verificationId) => {
    // Pass verificationId
  });
</code></pre>
<p>After invoking <code>verifyPhoneNumber</code> OTP will be sent to given mobile number. then the last process to be required is to verify the <code>otp</code> and generated <code>verificationId</code> for this again we’re going to use a function <code>signInAndRetrieveDataWithCredential</code> from <code>firebase-js-sdk</code>.</p>
<pre><code class="language-js">const credential = firebase.auth.PhoneAuthProvider.credential(
  verificationId,
  otp
);

auth
  .signInAndRetrieveDataWithCredential(credential)
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    // Handle error
  });
</code></pre>
<p>Done! If <code>otp</code> and, <code>verificationId</code> verify successfully automatically your registered listener <code>onAuthStateChanged</code> will be invoked.</p>
<h2>References:</h2>
<ul>
<li><a href="https://github.com/firebase/firebase-js-sdk">firebase-js-sdk</a></li>
<li><a href="https://github.com/chemerisuk/cordova-plugin-firebase-authentication">cordova-plugin-firebase-authentication</a></li>
</ul>
<p><a href="https://medium.com/@BHAR4T/cordova-with-firebase-phone-authentication-without-captcha-6663427920d9">Read on Medium</a></p>
]]></content:encoded>
            <author>bhar4t@outlook.com (Bharat Sahu)</author>
            <enclosure url="https://webkoof.in/img/cordova_firebase.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Generate incremental Firebase Firestore order/number vs ordered document ID]]></title>
            <link>https://webkoof.in/articles/Generate-incremental-Firebase-Firestore-order-or-number-vs-ordered-document-ID</link>
            <guid isPermaLink="false">https://webkoof.in/articles/Generate-incremental-Firebase-Firestore-order-or-number-vs-ordered-document-ID</guid>
            <pubDate>Sun, 26 Jan 2020 00:00:00 GMT</pubDate>
            <description><![CDATA[I don’t recommend custom document ID over Firestore auto-generated ids cause the scalability comes from how Firestore spreads the document out over its storage layer. In a simplified way: sequential IDs have more hashing collisions..]]></description>
            <content:encoded><![CDATA[<p>Before going for incremental Firestore order or incremental document ID please go through <a href="https://firebase.google.com/docs/firestore/manage-data/add-data">Firestore documentation</a> you’ll get some use cases there with an important note:</p>
<blockquote>
<p>Important: Unlike "push IDs" in the Firebase Realtime Database, Cloud Firestore auto-generated IDs do not provide any automatic ordering. If you want to be able to order your documents by creation date, you should store a timestamp as a field in the documents.</p>
</blockquote>
<p>I don’t recommend custom document ID over Firestore auto-generated ids cause the scalability comes from how Firestore spreads the document out over its storage layer. In a simplified way: sequential IDs have more hashing collisions, which means you hit write limitations sooner. Having more random IDs ensures the writes are spread out evenly across the storage layer. At the reading, there is no such bottleneck, which is why the recommended approach is to use random keys and a field for ordering upon reads.</p>
<p>Before starting it requires some basic knowledge of <a href="https://firebase.google.com/docs/firestore/manage-data/transactions">Firestore transactions</a>. And, if you want to store your data a field with custom incremental order, Let’s start…</p>
<p>Suppose we have 2 collections first as <em>Organisations</em> and the other is <em>Purchases</em>. I have an application that has organizations that can maintain their purchase records on Firebase Firestore and, Every organization will have its incremental serial number for their respective purchases. quick look of both objects:</p>
<pre><code class="language-json">organisation: {
  name: 'traderA',
  serialNumberGenerated: 0,
}
</code></pre>
<pre><code class="language-json">purchase: {
  created_at: new  Date(),
  amount: 889.99,
  serialNumber: 'traderA_025'   // Can be Number or Alphanumeric
}
</code></pre>
<p>Now, The <code>serialNumber</code> can be stored with purchase document two types, first as custom <code>document_id</code> or it can be stored as an object field/property. As we already talked about storing data with custom <code>document_id</code> is an anti-pattern, I don’t recommend custom <code>document_id</code>. But we can maintain a field/property in an ordered way.</p>
<p>Before starting transactions we need Firestore document reference of the selected organization and another reference from <em>purchases</em> with a random <code>document_id</code> to be stored with data.</p>
<pre><code class="language-js">// Create a reference to the organisations doc.
const orgRef = db.collection("organisations").doc("traderA_docId");

// Get random document id for purchases
const purchaseRef = db.collection("purchases").doc();
</code></pre>
<p>After this, we need to fetch serial numbers (<code>serialNumberGenerated</code>) till generated for <em>purchases</em> which is stored in <em>organizations</em> for a particular organization. For the next purchase data, it will be incremented by one to maintain order and, must be stored in both organizations and purchase documents. We’ll do this work inside transactions.</p>
<pre><code class="language-js">return db
  .runTransaction((trx) => {
    return trx.get(orgRef).then((orgDoc) => {
      if (!orgDoc.exists) throw "Document does not exist!";

      // Increment one serialNumberGenerated to the organisations.
      const nextSerial = orgDoc.data().serialNumberGenerated + 1;

      trx.set(purchaseRef, {
        created_at: new Date(),
        amount: 888.99,
        serialNumber: nextSerial, // OR concat with String.
      });

      trx.update(orgRef, { serialNumberGenerated: nextSerial });
    });
  })
  .then(() => console.log("Transaction successfully committed!"))
  .catch((error) => console.log("Transaction failed: ", error));
</code></pre>
<p>Note:</p>
<ol>
<li>You can’t run <strong>transactions</strong> when <strong>offline</strong>.</li>
<li>Increment operation could be done using function <code>FieldValue.increment</code>.</li>
</ol>
<p><a href="https://medium.com/@BHAR4T/generate-incremental-firebase-firestore-order-number-vs-ordered-document-id-d03e0ce9d4a5">Read on Medium</a></p>
]]></content:encoded>
            <author>bhar4t@outlook.com (Bharat Sahu)</author>
            <enclosure url="https://webkoof.in/img/firebase_increment.jpeg" length="0" type="image/jpeg"/>
        </item>
    </channel>
</rss>