<?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[Tron Codes]]></title><description><![CDATA[Hello, I'm Palash Dhavle, a passionate software developer with a Master's Degree in Computer Applications. I specialize in crafting Python and JavaScript code t]]></description><link>https://blog.troncodes.in</link><generator>RSS for Node</generator><lastBuildDate>Thu, 30 Apr 2026 11:28:31 GMT</lastBuildDate><atom:link href="https://blog.troncodes.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Quick and Easy Supabase CLI Local Setup Guide]]></title><description><![CDATA[Yes, Supabase is powerful, but hitting production for every tweak? That’s a recipe for slow dev, wasted free-tier limits, and possible oops moments.
Instead, set up Supabase locally with the CLI. It’s faster, safer, and perfect for version control. Y...]]></description><link>https://blog.troncodes.in/quick-and-easy-supabase-cli-local-setup-guide</link><guid isPermaLink="true">https://blog.troncodes.in/quick-and-easy-supabase-cli-local-setup-guide</guid><category><![CDATA[supabase]]></category><category><![CDATA[Developer]]></category><category><![CDATA[backend]]></category><category><![CDATA[cli]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Mon, 09 Jun 2025 07:43:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1749454896379/e089d812-9dee-4b80-9acb-3c98cc041e1e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Yes, Supabase is powerful, but hitting production for every tweak? That’s a recipe for slow dev, wasted free-tier limits, and possible oops moments.</p>
<p>Instead, set up Supabase locally with the CLI. It’s faster, safer, and perfect for version control. Your teammates (and future self) will thank you when everything’s reproducible and just works.  </p>
<p>with tiny bit of setup and understanding of how things work you can make your setup solid from day one.</p>
<h2 id="heading-install-supabase-using-node">Install Supabase using node</h2>
<p>I’m going to keep things simple and install it with node using NPM. if you want install it differently you can check the Supabase CLI <a target="_blank" href="https://supabase.com/docs/guides/local-development/cli/getting-started?queryGroups=platform&amp;platform=npm&amp;queryGroups=access-method&amp;access-method=analytics">install guide</a>.</p>
<pre><code class="lang-bash">npm install supabase --save-dev
</code></pre>
<h2 id="heading-initialize-supabase">Initialize Supabase</h2>
<pre><code class="lang-bash">npx supabase init
</code></pre>
<h2 id="heading-start-supabase">Start Supabase</h2>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">You need to have <a target="_self" href="https://www.docker.com/products/docker-desktop/">docker desktop</a> installed on your system for this to work</div>
</div>

<pre><code class="lang-bash">npx supabase start
</code></pre>
<p>this will download all the docker images and start your Supabase stack locally. You would see output like this <em>(obviously they are not my real secrets)</em> you would get your own.</p>
<pre><code class="lang-plaintext">Started supabase local development setup.

         API URL: http://127.0.0.1:54321
     GraphQL URL: http://127.0.0.1:54321/graphql/v1
  S3 Storage URL: http://127.0.0.1:54321/storage/v1/s3
          DB URL: postgresql://postgres:postgres@127.0.0.1:54322/postgres
      Studio URL: http://127.0.0.1:54323
    Inbucket URL: http://127.0.0.1:54324
      JWT secret: super-secret-jwt-token-with-at-least-32-characters-long
        anon key: eujnsdfnjkafwfnIkpXVCJ9.eyJpc3MiOiJzinjsfjnsfub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WkjnadsfonjdsfonigdDMblYTn_I0
service_role key: eyafsKJsfIgsbks80hinjoUbonCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwichabjfjsa8oIJJnnjnlUHJk5Nn0.EGIM96ajhbjifaoiHIs81IU
   S3 Access Key: 62sdf729ahbsiouhfff351asa23cf
   S3 Secret Key: 85ojsnfosoijwfiowefvs742isdfjnfweu907
       S3 Region: local
</code></pre>
<p>Now we can go on <strong>Studio URL</strong> to get started</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749451981095/adda4db6-b684-45ad-aef0-2e475cc96e76.png" alt class="image--center mx-auto" /></p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">I would recommend to <a target="_self" class="notion-link-token notion-focusable-token notion-enable-hover" href="https://docs.deno.com/runtime/getting_started/installation/">install deno</a> when you are running Supabase locally as Supabase uses deno runtimes to execute edge functions and installing deno and its <strong>IntelliSence </strong>extension would help you.</div>
</div>

<h2 id="heading-connect-to-your-production-env">Connect to your production env</h2>
<p>there are two different ways to connect to the prod environment. either you use a PAT token which you can generate from this <a target="_blank" href="https://supabase.com/dashboard/account/tokens">link</a> and use the token to login or use browser login.</p>
<ol>
<li><p><strong>Browser login</strong></p>
<p> run the following command</p>
<pre><code class="lang-plaintext"> npx supabase login
</code></pre>
<p> <strong>Output</strong></p>
<pre><code class="lang-plaintext"> Hello from Supabase! Press Enter to open browser and login automatically.
</code></pre>
<p> If you are logged into Supabase in your browser you should see this screen on the browser.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749452307397/43c9d8bf-2567-4684-bfa1-893fa5d03b81.png" alt class="image--center mx-auto" /></p>
<p> now go back to your command line and enter the code. This would automatically create PAT token for you and set it in your local env.</p>
</li>
<li><p><strong>Manually generating PAT (Personal Access Token)</strong></p>
<ul>
<li><p>generate from this <a target="_blank" href="https://supabase.com/dashboard/account/tokens">link</a></p>
</li>
<li><p>run the following command</p>
<pre><code class="lang-plaintext">  $env:SUPABASE_ACCESS_TOKEN="sbp_a6cc1610147"; npx supabase link
</code></pre>
  <div data-node-type="callout">
  <div data-node-type="callout-emoji">💡</div>
  <div data-node-type="callout-text">replace the token with your token.</div>
  </div>


</li>
</ul>
</li>
</ol>
<h2 id="heading-link-project">Link project</h2>
<pre><code class="lang-bash">npx supabase link
</code></pre>
<ol>
<li><p>select the project.</p>
</li>
<li><p>enter the Database password</p>
<ol>
<li><p>you can find the password under. <code>Project Settings</code> &gt; <code>Configuration</code> &gt; <code>Database</code></p>
</li>
<li><p>hit reset password and generate a new password</p>
</li>
<li><p>copy that password</p>
</li>
</ol>
</li>
</ol>
<p>and you are done. now you can sync the database to production database using the following commands.</p>
<ol>
<li><p>pull configs. this would pull migrations and configs from the production</p>
<pre><code class="lang-bash"> npx supabase db pull
</code></pre>
</li>
<li><p>push configs</p>
<pre><code class="lang-bash"> npx supabase db push
</code></pre>
</li>
</ol>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">You need to enter Database password if you have not already in the beginning.</div>
</div>

<p>next you run the command.</p>
<pre><code class="lang-bash">npx supabase db reset
</code></pre>
<p>this will reset the local database and apply all the migrations</p>
<p>for more details check: <a target="_blank" href="https://supabase.com/docs/reference/cli/supabase-db-reset">Supabase CLI reference</a></p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>Note:</strong> If you’ve made changes to protected schemas like <code>auth</code> in production, <strong>Supabase won’t pull those by default</strong> when running <code>db pull</code> — and that’s usually for good reason. Pulling Supabase-managed migrations can cause serious headaches if you're not careful.</div>
</div>

<p>If you need to add something custom (like a trigger on <code>auth.users</code> post-signup), it’s better to <strong>create a local migration</strong> (will see how to do this next), push it to Git, and let your teammates pick it up. Since the base <code>auth</code> schema already exists in production, make sure your migration includes proper checks — e.g., <code>IF NOT EXISTS</code> — to avoid blowing things up.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>Heads up: </strong>when i did the process for the first time my migrations did not get applied. I stopped all the containers using the command <code>npx supabase stop</code> and than I started them again using <code>npx supabase start</code> and redid the process of pulling the data and resetting the database and it worked. it may have caused because when i ran the <code>npx supabase db reset</code> command for the first time it started pulling docker images. even though I have ran the command <code>npx supabase start</code> beforehand.</div>
</div>

<h2 id="heading-migrations">Migrations</h2>
<p>In Supabase we need to create migrations to keep things in sync with local and prod. When we make changes locally we need to create migrations for version control so other devs working on the project are on the same page and also when other people make changes we can get those changes and push it to the production.</p>
<p>There are two ways to create migrations.</p>
<ol>
<li><p><strong>Create migration file manually</strong></p>
<ol>
<li><p><strong>Run the command</strong></p>
<pre><code class="lang-bash"> npx supabase migration new &lt;file name&gt;
</code></pre>
<p> example:</p>
<pre><code class="lang-bash"> npx supabase migration new new_migration
</code></pre>
</li>
<li><p>A<strong>dd content in the migration file</strong></p>
<p> for example lets say we want to add a trigger, this could be anything. such as creating a table</p>
<pre><code class="lang-sql"> <span class="hljs-comment">-- Add trigger to populate `profiles` when a new `auth.users` is created</span>
 <span class="hljs-keyword">do</span> $$
 <span class="hljs-keyword">begin</span>
   <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">exists</span> (
     <span class="hljs-keyword">select</span> <span class="hljs-number">1</span> <span class="hljs-keyword">from</span> pg_trigger <span class="hljs-keyword">where</span> tgname = <span class="hljs-string">'on_auth_user_created'</span>
   ) <span class="hljs-keyword">then</span>
     <span class="hljs-keyword">create</span> <span class="hljs-keyword">trigger</span> on_auth_user_created
       <span class="hljs-keyword">after</span> <span class="hljs-keyword">insert</span> <span class="hljs-keyword">on</span> auth.users
       <span class="hljs-keyword">for</span> <span class="hljs-keyword">each</span> <span class="hljs-keyword">row</span>
       <span class="hljs-keyword">execute</span> <span class="hljs-keyword">function</span> public.handle_new_user();
   <span class="hljs-keyword">end</span> <span class="hljs-keyword">if</span>;
 <span class="hljs-keyword">end</span>
 $$;
</code></pre>
</li>
<li><p><strong>Apply changes to local Database</strong></p>
<pre><code class="lang-sql"> npx supabase db <span class="hljs-keyword">reset</span>
</code></pre>
</li>
<li><p><strong>Push to git for version control</strong></p>
<p> this helps other people working on the project get the changes</p>
<pre><code class="lang-bash"> git add .
 git commit -m <span class="hljs-string">"Add safe trigger on auth.users to populate profiles"</span>
 git push origin main
</code></pre>
</li>
<li><p>Push to Supabase production</p>
<pre><code class="lang-sql"> npx supabase db push
</code></pre>
</li>
<li><p><strong>Make changes from the dashboard and generate migration</strong></p>
<p> You can make changes from the dashboard. like creating tables, adding or altering columns, creating functions etc.</p>
 <div data-node-type="callout">
 <div data-node-type="callout-emoji">💡</div>
 <div data-node-type="callout-text">There are limitation to this though. you cant run alter schema from auth and other protected schemas which are managed by Supabase from the Supabase dashboard directly. in that case you either use the SQL editor in Supabase dashboard or use the first method.</div>
 </div>

<ol>
<li><p><strong>Generate migration content</strong></p>
<pre><code class="lang-bash"> npx supabase db diff
</code></pre>
<p> if you have made changes related to protected schemas you need to add the schema flag and mention the schemas as Supabase don’t do it by default.</p>
<pre><code class="lang-bash"> npx supabase db diff --schema public,auth
</code></pre>
<p> this will auto generate the migration based on the changes and give the output in <code>stdout</code> on the terminal. like the following.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749453970890/efe02c37-6e53-4562-91dc-4edfa2cacb02.png" alt class="image--center mx-auto" /></p>
<p> just copy this content</p>
<p> you can use this to create a new migration by creating a new migration file</p>
</li>
</ol>
</li>
</ol>
</li>
</ol>
<p>        2. <strong>Create migration file</strong></p>
<pre><code class="lang-bash">        supabase migration new &lt;migration_name&gt;
</code></pre>
<p>        e:g</p>
<pre><code class="lang-bash">        supabase migration new schema_test
</code></pre>
<p>        and now copy the migration content into the generated file. the generate file should be inside the migrations folder with name something like this <code>20250609062017_schema_test</code></p>
<p>        or you can simply use the following command to write the content directly to the file.</p>
<pre><code class="lang-bash">        npx supabase db diff --schema public,auth --file migrations/20250609_add_trigger.sql
</code></pre>
        <div data-node-type="callout">
        <div data-node-type="callout-emoji">💡</div>
        <div data-node-type="callout-text">I would recommend generating the file using the command as it generates accurate timestamp.</div>
        </div>

<p>        once this is done you can follow the same process as method one to apply changes changes, push to production and version control  </p>
<p>Resources: <a target="_blank" href="https://supabase.com/docs/guides/local-development?queryGroups=package-manager&amp;package-manager=npm">Supabase docs</a></p>
]]></content:encoded></item><item><title><![CDATA[Transform into anyone using this crazy AI tool]]></title><description><![CDATA[Welcome to the easiest guide you'll find for installing Deep Live Cam, a fun and impressive live deepfake tool. Even if you’re not technical, don’t worry, we’ve got your back.
What is Deep Live Cam?
It's a tool that lets you transform your face in re...]]></description><link>https://blog.troncodes.in/transform-into-anyone-using-this-crazy-ai-tool</link><guid isPermaLink="true">https://blog.troncodes.in/transform-into-anyone-using-this-crazy-ai-tool</guid><category><![CDATA[Deepfake]]></category><category><![CDATA[AI]]></category><category><![CDATA[#ai-tools]]></category><category><![CDATA[technology]]></category><category><![CDATA[Magic]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Fri, 09 May 2025 18:58:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cfFspy3GWpw/upload/fc8db36b8ba25df3803f7bc21f23323d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to the easiest guide you'll find for installing <strong>Deep Live Cam</strong>, a fun and impressive live deepfake tool. Even if you’re not technical, don’t worry, we’ve got your back.</p>
<h2 id="heading-what-is-deep-live-cam">What is Deep Live Cam?</h2>
<p>It's a tool that lets you transform your face in real time using AI magic. Think FaceSwap, but live. You can prank your friends or just explore the tech, it’s all local (on your computer), so no data is sent anywhere. Your secret's safe.</p>
<hr />
<h2 id="heading-what-youll-need-first">What You'll Need First</h2>
<p>Before installing, let's get the essentials out of the way. It’s like setting the table before a feast.</p>
<h3 id="heading-1-install-python-310-is-required">1. Install Python (3.10 is required)</h3>
<p>Head over to <a target="_blank" href="https://www.python.org/downloads/release/python-3100/">python.org</a> and download Python 3.10.</p>
<blockquote>
<p>Make sure you check the box that says <strong>"Add Python to PATH"</strong> during installation.</p>
</blockquote>
<h3 id="heading-2-install-git">2. Install Git</h3>
<p>Grab it from <a target="_blank" href="https://git-scm.com/">git-scm.com</a> and install like you would any other app.</p>
<h3 id="heading-3-install-ffmpeg">3. Install <code>ffmpeg</code></h3>
<p>This tool handles video magic.</p>
<ul>
<li><p>Press <code>Windows + R</code>, type <code>powershell</code>, then hit enter.</p>
</li>
<li><p>Paste this in and press Enter:</p>
</li>
</ul>
<pre><code class="lang-bash">iex (irm ffmpeg.tc.ht)
</code></pre>
<p>This command:</p>
<ul>
<li><p><code>iex</code> = run the downloaded command as a script</p>
</li>
<li><p><code>irm</code> = download a script from the web (shorthand for <code>Invoke-RestMethod</code>)</p>
</li>
<li><p>The rest points to a safe script to auto-install ffmpeg on Windows.</p>
</li>
<li><p>after the script runs you'll get three options and you need to choose number 3</p>
</li>
<li><p>still stuck? refer this video: <a target="_blank" href="https://www.youtube.com/watch?v=OlNWCpFdVMA">https://www.youtube.com/watch?v=OlNWCpFdVMA</a></p>
</li>
</ul>
<h3 id="heading-4-install-visual-studio-2022-runtimes-windows-only">4. Install Visual Studio 2022 Runtimes (Windows only)</h3>
<p>Download from: <a target="_blank" href="https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170">Microsoft Visual C++ Redistributable</a></p>
<blockquote>
<p>Choose the version matching your system (x64 for most users).</p>
</blockquote>
<hr />
<h2 id="heading-clone-amp-set-it-up">Clone &amp; Set It Up</h2>
<h3 id="heading-1-open-terminal-command-prompt-and-paste-the-commands">1. Open Terminal / Command Prompt and paste the commands:</h3>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> https://github.com/hacksider/Deep-Live-Cam.git
</code></pre>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> Deep-Live-Cam
</code></pre>
<h3 id="heading-2-download-the-models">2. Download the Models</h3>
<p>Download these two files:</p>
<ul>
<li><p><a target="_blank" href="https://huggingface.co/hacksider/deep-live-cam/resolve/main/GFPGANv1.4.pth"><code>GFPGANv1.4</code></a></p>
</li>
<li><p><a target="_blank" href="https://huggingface.co/hacksider/deep-live-cam/resolve/main/inswapper_128_fp16.onnx"><code>inswapper_128_fp16.onnx</code></a></p>
</li>
</ul>
<p>Put them into the <strong>models</strong> folder inside the cloned Deep-Live-Cam directory. No need to unzip or rename.</p>
<h3 id="heading-3-set-up-virtual-environment-optional-but-smart">3. Set Up Virtual Environment (Optional, but Smart)</h3>
<p>Helps prevent your computer from becoming a dependency mess.</p>
<h4 id="heading-for-windows">For Windows:</h4>
<pre><code class="lang-bash">python -m venv venv
</code></pre>
<pre><code class="lang-bash">venv\Scripts\activate
</code></pre>
<pre><code class="lang-bash">pip install -r requirements.txt
</code></pre>
<h4 id="heading-for-macos-apple-silicon">For macOS (Apple Silicon):</h4>
<pre><code class="lang-bash">brew install python@3.10
</code></pre>
<pre><code class="lang-bash">brew install python-tk@3.10
</code></pre>
<pre><code class="lang-bash">python3.10 -m venv venv
</code></pre>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> venv/bin/activate
</code></pre>
<pre><code class="lang-bash">pip install -r requirements.txt
</code></pre>
<blockquote>
<p>If you get <code>_tkinter</code> errors, reinstall tkinter using <code>brew reinstall python-tk@3.10</code></p>
</blockquote>
<h4 id="heading-for-linux">For Linux:</h4>
<pre><code class="lang-bash">python3.10 -m venv venv
</code></pre>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> venv/bin/activate
</code></pre>
<pre><code class="lang-bash">pip install -r requirements.txt
</code></pre>
<h3 id="heading-4-fix-missing-module-error-pygrabber">4. Fix Missing Module Error (pygrabber)</h3>
<p>You might see an error like <code>ModuleNotFoundError: No module named 'pygrabber'</code> Just run:</p>
<pre><code class="lang-bash">pip install pygrabber
</code></pre>
<hr />
<h2 id="heading-time-to-run-it">Time to Run It!</h2>
<p>You can run the tool with this command:</p>
<pre><code class="lang-bash">python run.py
</code></pre>
<p>This downloads additional files (~300MB), so have your Wi-Fi ready.</p>
<h2 id="heading-gpu-acceleration-if-you-want-speed">GPU Acceleration (If You Want Speed)</h2>
<h3 id="heading-cuda-nvidia-only">CUDA (Nvidia Only)</h3>
<p><strong>Only try this if you're feeling adventurous and have an Nvidia GPU.</strong></p>
<p><strong>Steps:</strong></p>
<ol>
<li><p>Install CUDA Toolkit 11.8 from <a target="_blank" href="https://developer.nvidia.com/cuda-11-8-0-download-archive">Nvidia</a></p>
</li>
<li><p>You also need a full Visual Studio 2022 installation with C++ workload enabled.</p>
</li>
</ol>
<blockquote>
<p>It didn't work well on a GTX 3050 for me. YMMV.</p>
</blockquote>
<p>Then run:</p>
<pre><code class="lang-bash">pip uninstall onnxruntime onnxruntime-gpu
</code></pre>
<pre><code class="lang-bash">pip install onnxruntime-gpu==1.16.3
</code></pre>
<pre><code class="lang-bash">python run.py --execution-provider cuda
</code></pre>
<h3 id="heading-apple-silicon-m1m2m3">Apple Silicon (M1/M2/M3)</h3>
<pre><code class="lang-bash">pip uninstall onnxruntime onnxruntime-silicon
</code></pre>
<pre><code class="lang-bash">pip install onnxruntime-silicon==1.13.1
</code></pre>
<pre><code class="lang-bash">python3.10 run.py --execution-provider coreml
</code></pre>
<h3 id="heading-windows-directml">Windows (DirectML)</h3>
<pre><code class="lang-bash">pip uninstall onnxruntime onnxruntime-directml
</code></pre>
<pre><code class="lang-bash">pip install onnxruntime-directml==1.15.1
</code></pre>
<pre><code class="lang-bash">python run.py --execution-provider directml
</code></pre>
<h3 id="heading-intel-openvino">Intel (OpenVINO)</h3>
<pre><code class="lang-bash">pip uninstall onnxruntime onnxruntime-openvino
</code></pre>
<pre><code class="lang-bash">pip install onnxruntime-openvino==1.15.0
</code></pre>
<pre><code class="lang-bash">python run.py --execution-provider openvino
</code></pre>
<hr />
<h2 id="heading-troubleshooting-tips">Troubleshooting Tips</h2>
<ul>
<li><p>If your models don’t load: double-check they’re in the right <strong>models/</strong> folder.</p>
</li>
<li><p>If Python 3.10 isn’t being used:</p>
<ul>
<li>On macOS, always use <code>python3.10</code>, not <code>python</code></li>
</ul>
</li>
<li><p>Conflicting Python versions?</p>
</li>
</ul>
<pre><code class="lang-bash">brew list | grep python
brew uninstall --ignore-dependencies python@3.11 python@3.13
brew cleanup
</code></pre>
<hr />
<h2 id="heading-final-notes">Final Notes</h2>
<ul>
<li><p>The tool works fine with just CPU, though it’ll be slower.</p>
</li>
<li><p>GPU acceleration is cool, but not mandatory.</p>
</li>
<li><p>If you hit a wall, don’t panic—90% of the time it’s a missing install.</p>
</li>
</ul>
<blockquote>
<p>Now go deepfake responsibly.</p>
</blockquote>
<h2 id="heading-credits">Credits</h2>
<p>Deep Live Cam is created and maintained by <a target="_blank" href="https://github.com/hacksider/Deep-Live-Cam?tab=readme-ov-file">hacksider on GitHub</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Effortless Secure Login & Signup in Minutes with Next.js and clerk]]></title><description><![CDATA[Prerequisites
Make sure you have:

Node.js (LTS version) installed

npm or yarn as a package manager

Git installed (optional but recommended)  



Setting Up a Next.js Project
Open your terminal and run:
npx create-next-app@latest my-clerk-app
cd my...]]></description><link>https://blog.troncodes.in/effortless-secure-login-signup-in-minutes</link><guid isPermaLink="true">https://blog.troncodes.in/effortless-secure-login-signup-in-minutes</guid><category><![CDATA[authentication]]></category><category><![CDATA[Security]]></category><category><![CDATA[nestjs]]></category><category><![CDATA[Clerk.dev]]></category><category><![CDATA[React]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Sat, 08 Feb 2025 18:03:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739036774645/6a470c50-faac-4a99-b876-b49de9a356cc.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-prerequisites"><strong>Prerequisites</strong></h3>
<p>Make sure you have:</p>
<ul>
<li><p><strong>Node.js</strong> (LTS version) installed</p>
</li>
<li><p><strong>npm</strong> or <strong>yarn</strong> as a package manager</p>
</li>
<li><p><strong>Git</strong> installed (optional but recommended)  </p>
</li>
</ul>
<hr />
<h3 id="heading-setting-up-a-nextjs-project"><strong>Setting Up a Next.js Project</strong></h3>
<p>Open your terminal and run:</p>
<pre><code class="lang-bash">npx create-next-app@latest my-clerk-app
<span class="hljs-built_in">cd</span> my-clerk-app
</code></pre>
<p>or using yarn:</p>
<pre><code class="lang-bash">yarn create next-app my-clerk-app
<span class="hljs-built_in">cd</span> my-clerk-app
</code></pre>
<p>Start the development server:</p>
<pre><code class="lang-bash">npm run dev
</code></pre>
<p>or</p>
<pre><code class="lang-bash">yarn dev
</code></pre>
<p>Now, your Next.js project is ready! Next, we'll integrate Clerk for authentication.</p>
<h3 id="heading-integrating-clerk">Integrating Clerk</h3>
<p>Create an account for clerk by going on <a target="_blank" href="https://clerk.com/">https://clerk.com/</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739033535433/928b037f-23b6-4ae5-889d-fa1a4ee826a3.png" alt class="image--center mx-auto" /></p>
<p>Once you sign in you should see this. Select all the forms of authentication you want and click on Create application</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739033591102/096dc6f5-eb71-415d-b2f5-d3f05333fde0.png" alt class="image--center mx-auto" /></p>
<p>I simply follow the clerk’s instructions on how to install clerk and set up the env variables and setup the middle ware.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739033658151/51030784-adb8-46dd-b17b-b2a156447d5d.png" alt class="image--center mx-auto" /></p>
<p>I usually follow everything as clerk says until setting up the middleware part. for the clerk provider I like to do things slightly differently.</p>
<ul>
<li><p>I like to create a separate folder in my <code>src</code> directory called providers</p>
</li>
<li><p>There i create a file called <code>index.tsx</code> where I create a component called providers and wrap the children of provider component into all the other providers which I’ll be using.</p>
</li>
</ul>
<p><strong>src/providers/index.tsx</strong></p>
<pre><code class="lang-typescript"><span class="hljs-string">'use client'</span>
<span class="hljs-keyword">import</span> { ClerkProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">'@clerk/nextjs'</span>
<span class="hljs-keyword">import</span> { nhost } <span class="hljs-keyword">from</span> <span class="hljs-string">'../lib/nhost'</span>

<span class="hljs-keyword">interface</span> ProviderProps {
  children: React.ReactNode
}

<span class="hljs-keyword">const</span> Provider: React.FC&lt;ProviderProps&gt; = <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
      &lt;ClerkProvider&gt;
        {children}
      &lt;/ClerkProvider&gt;
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Provider
</code></pre>
<ul>
<li>Then I use this provider component to wrap my main content. This helps me keep my code clean</li>
</ul>
<p><strong>src/app/layout.tsx</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> <span class="hljs-keyword">type</span> { Metadata } <span class="hljs-keyword">from</span> <span class="hljs-string">"next"</span>;
<span class="hljs-keyword">import</span> { Geist, Geist_Mono } <span class="hljs-keyword">from</span> <span class="hljs-string">"next/font/google"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"./globals.css"</span>;
<span class="hljs-keyword">import</span> Provider <span class="hljs-keyword">from</span> <span class="hljs-string">"@/providers"</span>;

<span class="hljs-keyword">const</span> geistSans = Geist({
    variable: <span class="hljs-string">"--font-geist-sans"</span>,
    subsets: [<span class="hljs-string">"latin"</span>],
});

<span class="hljs-keyword">const</span> geistMono = Geist_Mono({
    variable: <span class="hljs-string">"--font-geist-mono"</span>,
    subsets: [<span class="hljs-string">"latin"</span>],
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> metadata: Metadata = {
    title: <span class="hljs-string">"Create Next App"</span>,
    description: <span class="hljs-string">"Generated by create next app"</span>,
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">RootLayout</span>(<span class="hljs-params">{
    children,
}: Readonly&lt;{
    children: React.ReactNode;
}&gt;</span>) </span>{
    <span class="hljs-keyword">return</span> (
        &lt;html lang=<span class="hljs-string">"en"</span>&gt;
            &lt;body
                className={<span class="hljs-string">`<span class="hljs-subst">${geistSans.variable}</span> <span class="hljs-subst">${geistMono.variable}</span> antialiased`</span>}
            &gt;
                &lt;Provider&gt;
                    {children}
                &lt;/Provider&gt;
            &lt;/body&gt;
        &lt;/html&gt;
    );
}
</code></pre>
<ul>
<li>Then we can simply put the <strong>signin</strong> button on the <strong>app/page.tsx</strong> file like this. and run the project using yarn dev or npm run dev</li>
</ul>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { SignedIn, SignedOut, SignInButton, UserButton } <span class="hljs-keyword">from</span> <span class="hljs-string">"@clerk/nextjs"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Home</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> (
        &lt;div className=<span class="hljs-string">"flex justify-center items-center w-full h-svh"</span>&gt;
            &lt;div className=<span class="hljs-string">"text-center flex flex-col items-center justify-center gap-3"</span>&gt;
                &lt;p className=<span class="hljs-string">"text-3xl"</span>&gt;Clerk Basic Setup&lt;/p&gt;
                &lt;SignedOut&gt;
                    &lt;div className=<span class="hljs-string">"w-fit px-8 py-2 border border-gray-400 rounded-md"</span>&gt;
                        &lt;SignInButton /&gt;
                    &lt;/div&gt;
                &lt;/SignedOut&gt;

                &lt;SignedIn&gt;
                    &lt;div className=<span class="hljs-string">"w-fit px-8 py-2 border border-gray-400 rounded-md"</span>&gt;
                        &lt;UserButton /&gt;
                    &lt;/div&gt;
                &lt;/SignedIn&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    );
}
</code></pre>
<p>You are all set. You have ready to use authentication system on which you can build upon.</p>
<h3 id="heading-results">Results</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739036200714/86d00d45-f194-402d-9a39-8a7ac0e22a8c.png" alt class="image--center mx-auto" /></p>
<ul>
<li>Clicking on signup button will show you this which you can use to sign up</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739036324693/9ca8a251-42a5-4821-a177-2aaa293e3000.png" alt class="image--center mx-auto" /></p>
<p>On successful signup you can will be redirected to the same page which you were before than we can see that we can use the clerks in build account management.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739036375836/6b8b3768-6640-4637-b428-56c1f82aa183.gif" alt class="image--center mx-auto" /></p>
<p>we can check the dashboard and we’ll see that new account has been registered.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739036441003/6af04be9-b712-4f7b-af39-4272c149ec69.png" alt class="image--center mx-auto" /></p>
<p>Thanks for taking the time to read my blog! I’d love to hear your thoughts, feel free to share your feedback or ask any questions in the comments. Your input helps me improve and create better content.</p>
<p>Until next time!</p>
]]></content:encoded></item><item><title><![CDATA[TypeScript Unlocked: Interfaces]]></title><description><![CDATA[💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.


Interfaces...]]></description><link>https://blog.troncodes.in/typescript-unlocked-interfaces</link><guid isPermaLink="true">https://blog.troncodes.in/typescript-unlocked-interfaces</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[clean code]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[coding]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Thu, 09 May 2024 10:50:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715251736944/6e4def8f-73a0-4c2b-8bb9-800ebb4edf2a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This article is a part of <a target="_blank" href="https://blog.troncodes.com/series/typescript-unlocked">TypeScript Unlocked</a> Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.</div>
</div>

<p>Interfaces works similar to type keyword which we have discussed earlier in the series. Interface allows us to define the structure of the object just like <strong>type</strong> but there are few differences.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> User {
    <span class="hljs-keyword">readonly</span> id : <span class="hljs-built_in">number</span> <span class="hljs-comment">// setting this as readonly field</span>
    name: <span class="hljs-built_in">string</span> 
    age?: <span class="hljs-built_in">number</span> <span class="hljs-comment">// setting this as optional field</span>
    isLoggedIn(): <span class="hljs-built_in">string</span> <span class="hljs-comment">// method named isLoggedIn which returns string</span>
    getStatus: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">string</span> <span class="hljs-comment">// similar methods can also be defined using this syntax</span>
    getName(id:<span class="hljs-built_in">number</span>) : <span class="hljs-built_in">string</span>
}

<span class="hljs-keyword">const</span> user: User = {
    id: <span class="hljs-number">1234321</span>,
    name: <span class="hljs-string">"Palash"</span>,
    isLoggedIn: <span class="hljs-function">()=&gt;</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"YES"</span>
    },
    getStatus: <span class="hljs-function">()=&gt;</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Online"</span>
    },
    getName:<span class="hljs-function">(<span class="hljs-params">id:<span class="hljs-number">2</span></span>)=&gt;</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"usr"</span> + id
    }
}
</code></pre>
<h2 id="heading-reopening-of-interface">Reopening of Interface</h2>
<p>Sometimes we may want to add some additional properties to our interfaces after they has been defined. For example, if you have imported some <strong>library</strong> and it has some interfaces which you want to update. You can use the following syntax but this changes the original interface as well so if you are using the original interface in the future you have to add the new property which you have added.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> User {
    <span class="hljs-keyword">readonly</span> id : <span class="hljs-built_in">number</span> <span class="hljs-comment">// setting this as readonly field</span>
    name: <span class="hljs-built_in">string</span> 
    age?: <span class="hljs-built_in">number</span> <span class="hljs-comment">// setting this as optional field</span>
    isLoggedIn(): <span class="hljs-built_in">string</span> <span class="hljs-comment">// method named isLoggedIn which returns string</span>
    getStatus: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">string</span> <span class="hljs-comment">// similar methods can also be defined using this syntax</span>
    getName(id:<span class="hljs-built_in">number</span>) : <span class="hljs-built_in">string</span>
}

<span class="hljs-keyword">interface</span> User { <span class="hljs-comment">// reopening the Interface </span>
    phone: <span class="hljs-built_in">number</span>
}

<span class="hljs-keyword">const</span> user: User = {
    id: <span class="hljs-number">1234321</span>,
    name: <span class="hljs-string">"Palash"</span>,
    phone: <span class="hljs-number">9898767852</span>,
    isLoggedIn: <span class="hljs-function">()=&gt;</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"YES"</span>
    },
    getStatus: <span class="hljs-function">()=&gt;</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Online"</span>
    },
    getName:<span class="hljs-function">(<span class="hljs-params">id:<span class="hljs-number">2</span></span>)=&gt;</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"usr"</span> + id
    }
}
</code></pre>
<h2 id="heading-inheritance">Inheritance</h2>
<p>we just saw how you can reopen an interface and add new properties but the drawback was it changes the original interface as well. So, if you want to update your interface but don't want to change the original one, we can use <strong>Inheritance. Inheritance</strong> establishes a relation between the parent interface and the child interface and both the interfaces are two separate interfaces. The child interface will have all the properties of the parent interface. One thing to note here is that unlike classes overriding methods of interfaces does not work.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> User {
    <span class="hljs-keyword">readonly</span> id : <span class="hljs-built_in">number</span> <span class="hljs-comment">// setting this as readonly field</span>
    name: <span class="hljs-built_in">string</span> 
    age?: <span class="hljs-built_in">number</span> <span class="hljs-comment">// setting this as optional field</span>
    isLoggedIn(): <span class="hljs-built_in">string</span> <span class="hljs-comment">// method named isLoggedIn which returns string</span>
    getStatus: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">string</span> <span class="hljs-comment">// similar methods can also be defined using this syntax</span>
    getName(id:<span class="hljs-built_in">number</span>) : <span class="hljs-built_in">string</span>
}

<span class="hljs-keyword">interface</span> Admin <span class="hljs-keyword">extends</span> User { <span class="hljs-comment">// extending the Admin interface from user</span>
    role: <span class="hljs-built_in">string</span>
}

<span class="hljs-keyword">const</span> admin: Admin = {
    id: <span class="hljs-number">1234321</span>,
    name: <span class="hljs-string">"Palash"</span>,
    role: <span class="hljs-string">"Admin"</span>,
    isLoggedIn: <span class="hljs-function">()=&gt;</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"YES"</span>
    },
    getStatus: <span class="hljs-function">()=&gt;</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Online"</span>
    },
    getName:<span class="hljs-function">(<span class="hljs-params">id:<span class="hljs-number">2</span></span>)=&gt;</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"usr"</span> + id
    }
}

}
</code></pre>
<h2 id="heading-interface-implements">Interface <code>implements</code></h2>
<p>In TypeScript, the <code>implements</code> keyword is used to enforce that a class must conform to a particular interface or multiple interfaces. When a class implements an interface, it means the class must contain all the members (properties and methods) defined in that interface.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> MyInterface {
    <span class="hljs-comment">// Properties or methods defined in the interface</span>
}

<span class="hljs-keyword">class</span> MyClass <span class="hljs-keyword">implements</span> MyInterface {
    <span class="hljs-comment">// Implementation of the properties or methods defined in the interface</span>
}
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Printable {
    print(): <span class="hljs-built_in">void</span>;
}

<span class="hljs-keyword">class</span> Document <span class="hljs-keyword">implements</span> Printable {
    print() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Printing document...'</span>); <span class="hljs-comment">// Implementing the 'print()' method from the 'Printable' interface</span>
    }
}

<span class="hljs-keyword">const</span> <span class="hljs-built_in">document</span> = <span class="hljs-keyword">new</span> Document();
<span class="hljs-built_in">document</span>.print(); <span class="hljs-comment">// Outputs: Printing document...</span>
</code></pre>
<p><strong>Syntax for Implementing Multiple Interfaces:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Interface1 {
    method1(): <span class="hljs-built_in">void</span>;
}

<span class="hljs-keyword">interface</span> Interface2 {
    method2(): <span class="hljs-built_in">void</span>;
}

<span class="hljs-keyword">class</span> MyClass <span class="hljs-keyword">implements</span> Interface1, Interface2 {
    method1() {
        <span class="hljs-comment">// Implementation for method1</span>
    }

    method2() {
        <span class="hljs-comment">// Implementation for method2</span>
    }
}
</code></pre>
<h2 id="heading-difference-between-type-aliases-and-interface">Difference between type Aliases and Interface</h2>
<p>Almost all features of an interface are available in type, the key distinction is that a type cannot be re-opened to add new properties vs an interface which is always extendable.</p>
<p><strong>TYPE</strong></p>
<p>Extending a type via intersections</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Animal = {
  name: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">type</span> Bear = Animal &amp; { 
  honey: <span class="hljs-built_in">boolean</span>;
}

<span class="hljs-keyword">const</span> bear = getBear();
bear.name;
bear.honey;
</code></pre>
<p>A type cannot be changed after being created</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Window = {
  title: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">type</span> Window = {
  ts: TypeScriptAPI;
}

 <span class="hljs-comment">// Error: Duplicate identifier 'Window'.</span>
</code></pre>
<p><strong>INTERFACE</strong></p>
<p>Extending an interface</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Animal {
  name: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">interface</span> Bear <span class="hljs-keyword">extends</span> Animal {
  honey: <span class="hljs-built_in">boolean</span>;
}

<span class="hljs-keyword">const</span> bear = getBear();
bear.name;
bear.honey;
</code></pre>
<p>Adding new fields to an existing interface</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Window {
  title: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">interface</span> Window {
  ts: TypeScriptAPI;
}

<span class="hljs-keyword">const</span> src = <span class="hljs-string">'const a = "Hello World"'</span>;
<span class="hljs-built_in">window</span>.ts.transpileModule(src, {});
</code></pre>
]]></content:encoded></item><item><title><![CDATA[TypeScript Unlocked: Tuple]]></title><description><![CDATA[💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.


Tuple is T...]]></description><link>https://blog.troncodes.in/typescript-unlocked-tuple</link><guid isPermaLink="true">https://blog.troncodes.in/typescript-unlocked-tuple</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[clean code]]></category><category><![CDATA[programmer]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Mon, 29 Apr 2024 10:53:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714387584616/b0497c4f-0fbf-48cb-909f-0f1a0c309d91.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This article is a part of <a target="_blank" href="https://blog.troncodes.com/series/typescript-unlocked">TypeScript Unlocked</a> Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.</div>
</div>

<p>Tuple is TypeScript Specific thing and we don’t have tuples in JavaScript. Tuples allow us to enforce order of types in an array.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> UserTuple: [<span class="hljs-built_in">number</span>,<span class="hljs-built_in">string</span>,<span class="hljs-built_in">boolean</span>]
UserTuple = [<span class="hljs-number">122</span>,<span class="hljs-string">"Palash"</span>,<span class="hljs-literal">true</span>] <span class="hljs-comment">// valid</span>
UserTuple = [<span class="hljs-number">122</span>,<span class="hljs-string">"Palash"</span>,<span class="hljs-string">"true"</span>] <span class="hljs-comment">// not valid</span>
</code></pre>
<p>We can define tuples using type as well</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> UserTuple = [<span class="hljs-built_in">number</span>,<span class="hljs-built_in">string</span>,<span class="hljs-built_in">boolean</span>] <span class="hljs-comment">// using type to define tuple</span>
<span class="hljs-keyword">let</span> UserTuple2: UserTuple = [<span class="hljs-number">122</span>,<span class="hljs-string">"Palash"</span>,<span class="hljs-literal">true</span>] <span class="hljs-comment">// valid</span>
<span class="hljs-keyword">let</span> UserTuple3: UserTuple = [<span class="hljs-number">122</span>,<span class="hljs-string">"Palash"</span>,<span class="hljs-string">"true"</span>] <span class="hljs-comment">// not valid</span>
</code></pre>
<h2 id="heading-bad-behavior">Bad behavior</h2>
<p>Tuple has some bad behavior which it should not do but it is allowed anyways.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// bad behaviour</span>
<span class="hljs-keyword">let</span> UserTuple: UserTuple = [<span class="hljs-number">122</span>,<span class="hljs-string">"Palash"</span>,<span class="hljs-literal">true</span>]
<span class="hljs-comment">// since user tuple is just an array we can use array methods on it. </span>
<span class="hljs-comment">// which should not happen because the purpose of tuple is to make </span>
<span class="hljs-comment">// sure we have all the menthioned data types in order</span>
UserTuple.push(<span class="hljs-string">"tf"</span>)
</code></pre>
<p>if you reached till here and you liked what you read don't forget LIKE to SHARE it with other people. if you have any feedback or suggestions feel free to use the comment section. Hope you tag along till the end of this series and strengthen your coding armor by adding TypeScript to it. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[TypeScript Unlocked: Union]]></title><description><![CDATA[💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.


Union enab...]]></description><link>https://blog.troncodes.in/typescript-unlocked-union</link><guid isPermaLink="true">https://blog.troncodes.in/typescript-unlocked-union</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[clean code]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[coding]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Thu, 18 Apr 2024 11:29:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1713438278753/12530ec4-a175-4723-8600-b7439a7e7e17.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This article is a part of <a target="_blank" href="https://blog.troncodes.com/series/typescript-unlocked">TypeScript Unlocked</a> Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.</div>
</div>

<p>Union enables us to assign two types to a single variable. Sometimes there might arise a situation where we might not know what kind of data will be encountering. In this kind of situation union comes in very handy. syntax for union is fairy straight forward we just use a pipe | between two types.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> height : <span class="hljs-built_in">number</span> | <span class="hljs-built_in">string</span> <span class="hljs-comment">// value can either be a number of a string</span>
height = <span class="hljs-number">5.2</span>
height = <span class="hljs-string">"5 foot 2 inches"</span>
</code></pre>
<h2 id="heading-union-in-functions">Union in functions</h2>
<p>It is very common scenario to use unions in functions. in the example below we are specifying that middle name should wither be string or null but one thing to consider here is we have applied a condition to first check if middle name is not null before calling <code>toUpperCase</code> method. if we did not do it TypeScript would have given us an error.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getFullName</span>(<span class="hljs-params">firstName:<span class="hljs-built_in">string</span>, middleName : <span class="hljs-built_in">string</span> | <span class="hljs-literal">null</span>, lastName : <span class="hljs-built_in">string</span></span>): <span class="hljs-title">string</span> </span>{
    <span class="hljs-keyword">if</span> (middleName)
        <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${firstName.toUpperCase()}</span> <span class="hljs-subst">${middleName.toUpperCase()}</span> <span class="hljs-subst">${lastName.toUpperCase()}</span>`</span>
    <span class="hljs-keyword">else</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${firstName.toUpperCase()}</span> <span class="hljs-subst">${lastName.toUpperCase()}</span>`</span>
 }
</code></pre>
<p>we can also make use of <code>Union</code> with type aliases</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> User = {
    firstName:<span class="hljs-built_in">string</span>
    middleName : <span class="hljs-built_in">string</span> | <span class="hljs-literal">null</span>
    lastName : <span class="hljs-built_in">string</span>
}
</code></pre>
<h2 id="heading-using-unions-in-arrays">Using Unions in Arrays</h2>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> ages1 : <span class="hljs-built_in">number</span>[] | <span class="hljs-built_in">string</span>[] = [<span class="hljs-number">22</span>,<span class="hljs-number">24</span>,<span class="hljs-number">25</span>] <span class="hljs-comment">// array can either be of number or string</span>
<span class="hljs-keyword">let</span> ages2 : <span class="hljs-built_in">number</span>[] | <span class="hljs-built_in">string</span>[] = [<span class="hljs-string">"22"</span>,<span class="hljs-string">"24"</span>,<span class="hljs-string">"25"</span>] <span class="hljs-comment">// array can either be of number or string</span>

<span class="hljs-keyword">let</span> ages5 : (<span class="hljs-built_in">number</span> | <span class="hljs-built_in">string</span>)[] = [<span class="hljs-number">22</span>,<span class="hljs-number">24</span>,<span class="hljs-string">"25"</span>] <span class="hljs-comment">// array elements can be both</span>
<span class="hljs-keyword">let</span> ages3 : <span class="hljs-built_in">Array</span>&lt;<span class="hljs-built_in">number</span> | <span class="hljs-built_in">string</span>&gt; = [<span class="hljs-number">22</span>,<span class="hljs-number">24</span>,<span class="hljs-string">"25"</span>] <span class="hljs-comment">// Another way of achieving the same results</span>
</code></pre>
<p>it works pretty much same in arrays as well. So this is almost everything you have to know about Union in TypeScript for you day to day stuff but if you are more curious and want some more details you can visit the <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types">Official Docs</a></p>
<p>if you reached till here and you liked what you read don't forget LIKE to SHARE it with other people. if you have any feedback or suggestions feel free to use the comment section. Hope you tag along till the end of this series and strengthen your coding armor by adding TypeScript to it. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[TypeScript Unlocked:  Readonly, Optional and Type Mixing]]></title><description><![CDATA[💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.


Readonly
R...]]></description><link>https://blog.troncodes.in/typescript-unlocked-readonly-optional-and-type-mixing</link><guid isPermaLink="true">https://blog.troncodes.in/typescript-unlocked-readonly-optional-and-type-mixing</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><category><![CDATA[clean code]]></category><category><![CDATA[coding]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Mon, 15 Apr 2024 10:28:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1713174375275/c9a0b613-bd15-41de-93c9-26f42ea4b981.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This article is a part of <a target="_blank" href="https://blog.troncodes.com/series/typescript-unlocked">TypeScript Unlocked</a> Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.</div>
</div>

<h2 id="heading-readonly">Readonly</h2>
<p>Readonly feature enables us to make properties of the an object <strong>readonly</strong>. This means we cannot change the value once it has been set, it can only be read.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> User = {
    <span class="hljs-keyword">readonly</span> id: <span class="hljs-built_in">number</span>, <span class="hljs-comment">// making id readonly</span>
    name: <span class="hljs-built_in">string</span>,
    age: <span class="hljs-built_in">number</span>,
}

<span class="hljs-keyword">const</span> user1: User = {
    id: <span class="hljs-number">123212</span>,
    name: <span class="hljs-string">"Palash Dhavle"</span>,
    age: <span class="hljs-number">24</span>
}

user1.id = <span class="hljs-number">31</span> <span class="hljs-comment">// this will raise an error</span>
</code></pre>
<p>I am using the <strong>readonly</strong> keyword for the <strong>id</strong> to make it <strong>readonly</strong>. Now we restrict changes to id property therefore the last line where I try to modify the <strong>id</strong> will throw an error. In some scenarios using <strong>readonly</strong> can make our code prone to less bugs.</p>
<h2 id="heading-optional">Optional</h2>
<p>Optional is very self explanatory. Sometimes we might not want to make it compulsory to add each and every property while creating an new instance of an object. So we mark some properties as optional.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> User = {
    <span class="hljs-keyword">readonly</span> id: <span class="hljs-built_in">number</span>, <span class="hljs-comment">// making id readonly</span>
    name: <span class="hljs-built_in">string</span>,
    age: <span class="hljs-built_in">number</span>,
    address?: <span class="hljs-built_in">string</span> <span class="hljs-comment">// making address optional</span>
}

<span class="hljs-keyword">const</span> user1: User = {
    id: <span class="hljs-number">123212</span>,
    name: <span class="hljs-string">"Palash Dhavle"</span>,
    age: <span class="hljs-number">24</span>
}

<span class="hljs-keyword">const</span> user2: User = {
    id: <span class="hljs-number">123213</span>,
    name: <span class="hljs-string">"Tony Stark"</span>,
    age: <span class="hljs-number">24</span>,
    address:<span class="hljs-string">"10880 Malibu Point, Malibu, California"</span>
}
</code></pre>
<p>To make a property optional we just have to put a question mark before the colon(:). In this case both <strong>user1</strong> and <strong>user2</strong> is valid because we have marked the property as <strong>optional</strong>.</p>
<h2 id="heading-type-mixing">Type mixing</h2>
<p>Sometimes we may need an object which is equivalent of combination of two three objects and each object may have more than 10+ keys. So in this situation instead of re-writing all the keys again and defining the type again we use something called type mixing.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> User = {
    <span class="hljs-keyword">readonly</span> id: <span class="hljs-built_in">number</span>, <span class="hljs-comment">// making id readonly</span>
    name: <span class="hljs-built_in">string</span>,
    age: <span class="hljs-built_in">number</span>,
    address?: <span class="hljs-built_in">string</span> <span class="hljs-comment">// making address optional</span>
}

<span class="hljs-keyword">type</span> BankInfo = {
    accNo: <span class="hljs-built_in">number</span>,
    accHolderName: <span class="hljs-built_in">string</span>
    branch: <span class="hljs-built_in">string</span>
}

<span class="hljs-keyword">type</span> education = {
    highestDegree: <span class="hljs-built_in">string</span>
    marks: <span class="hljs-built_in">number</span>
}

<span class="hljs-comment">// Using type Mixing</span>
<span class="hljs-keyword">type</span> userInfo = User &amp; BankInfo &amp; education

<span class="hljs-keyword">let</span> newUser: userInfo = {
    id: <span class="hljs-number">1234321</span>,
    name: <span class="hljs-string">"Palash Dhavle"</span>,
    age: <span class="hljs-number">19</span>,
    accNo: <span class="hljs-number">3456787653232</span>,
    accHolderName: <span class="hljs-string">"Palash"</span>,
    branch: <span class="hljs-string">"Mumbai"</span>,
    highestDegree: <span class="hljs-string">"Phd"</span>,
    marks: <span class="hljs-number">500</span>

}
</code></pre>
<p>This syntax is convenient when we face these kind of situation.</p>
<p>if you reached till here and you liked what you read don't forget LIKE to SHARE it with other people. if you have any feedback or suggestions feel free to use the comment section. Hope you tag along till the end of this series and strengthen your coding armor by adding TypeScript to it. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[TypeScript Unlocked: Type Aliases]]></title><description><![CDATA[💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.



Type Alia...]]></description><link>https://blog.troncodes.in/type-aliases</link><guid isPermaLink="true">https://blog.troncodes.in/type-aliases</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[webdevelopment]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[coding]]></category><category><![CDATA[clean code]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Mon, 15 Apr 2024 09:37:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1713172733142/18d0fd52-29ab-46ca-8340-a0859f2820f5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This article is a part of <a target="_blank" href="https://blog.troncodes.com/series/typescript-unlocked">TypeScript Unlocked</a> Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.</div>
</div>


<p>Type Aliases allows us to define the structure or shape of the object with the help of <strong>type</strong> keyword. Lets understand this with an example.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">{num1, num2}: {num1: <span class="hljs-built_in">number</span>, num2: <span class="hljs-built_in">number</span>}</span>): <span class="hljs-title">number</span>  </span>{
    <span class="hljs-keyword">return</span> num1 + num2
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sub</span>(<span class="hljs-params">{num1, num2}: {num1: <span class="hljs-built_in">number</span>, num2: <span class="hljs-built_in">number</span>}</span>): <span class="hljs-title">number</span>  </span>{
    <span class="hljs-keyword">return</span> num1 - num2
}

<span class="hljs-keyword">let</span> sum = add({num1: <span class="hljs-number">2</span>, num2: <span class="hljs-number">3</span>})
<span class="hljs-keyword">let</span> diff = sub({num1: <span class="hljs-number">3</span>, num2: <span class="hljs-number">2</span>})
<span class="hljs-built_in">console</span>.log(sum, diff);
</code></pre>
<p>In this code we define two functions, <strong>add</strong> and <strong>sub</strong>. Both the function accept the same type of object. So we need to define the same structure of object at two different places. Now if i want to add the functions to multiply and subtract I have to define the same thing again.</p>
<p>Type Aliases solves this problem. using <strong>type</strong> keyword we can define the structure or shape of the object only once and than use that type everywhere else.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Nums = {num1: <span class="hljs-built_in">number</span>, num2: <span class="hljs-built_in">number</span>}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">{num1, num2}: Nums</span>): <span class="hljs-title">number</span> </span>{
    <span class="hljs-keyword">return</span> num1 + num2
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sub</span>(<span class="hljs-params">{num1, num2}: Nums</span>): <span class="hljs-title">number</span>  </span>{
    <span class="hljs-keyword">return</span> num1 - num2
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mult</span>(<span class="hljs-params">{num1, num2}: Nums</span>): <span class="hljs-title">number</span> </span>{
    <span class="hljs-keyword">return</span> num1 * num2

}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">div</span>(<span class="hljs-params">{num1, num2}: Nums</span>): <span class="hljs-title">number</span>  </span>{
    <span class="hljs-keyword">return</span> num1 / num2
}

<span class="hljs-keyword">let</span> sum = add({num1: <span class="hljs-number">2</span>, num2: <span class="hljs-number">3</span>})
<span class="hljs-keyword">let</span> diff = sub({num1: <span class="hljs-number">3</span>, num2: <span class="hljs-number">2</span>})
<span class="hljs-keyword">let</span> prod = mult({num1: <span class="hljs-number">10</span>, num2: <span class="hljs-number">2</span>})
<span class="hljs-keyword">let</span> quot = div({num1: <span class="hljs-number">10</span>, num2: <span class="hljs-number">2</span>})
<span class="hljs-built_in">console</span>.log(sum, diff, prod, quot)
</code></pre>
<p>Type Aliases make the code much cleaner and easier to maintain. There is also something called <strong>interface</strong> which is similar to type. We will discuss about interfaces and how they are different from <strong>types</strong> as we go ahead with this series.</p>
<p>if you reached till here and you liked what you read don't forget to like and share it with other people. if you have any feedback or suggestions feel free to use the comment section. Hope you tag along till the end of this series and strengthen your coding armor by adding <strong>TypeScript</strong> to it. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[TypeScript Unlocked: Functions]]></title><description><![CDATA[💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.


Function A...]]></description><link>https://blog.troncodes.in/typescript-unlocked-functions</link><guid isPermaLink="true">https://blog.troncodes.in/typescript-unlocked-functions</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[functions]]></category><category><![CDATA[clean code]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Mon, 08 Apr 2024 15:19:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1712589485903/6f5e6a59-c94c-4265-91ad-5ab641905c52.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This article is a part of <a target="_blank" href="https://blog.troncodes.com/series/typescript-unlocked">TypeScript Unlocked</a> Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.</div>
</div>

<h2 id="heading-function-anatomy-for-typescript">Function Anatomy for typescript</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712588597396/2d806c34-717b-4bec-be49-843e88c69ea0.png" alt class="image--center mx-auto" /></p>
<p>Looking at the above image you can see how we do type checking when we write a function. If you don’t specify any type for the function parameter or function return type it will default to type of any which is not recommended when using type script.</p>
<h2 id="heading-understating-how-types-work-in-functions">Understating how types work in functions</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712588744985/46b99fcc-0018-498d-abc1-a75e892fd788.png" alt class="image--center mx-auto" /></p>
<p>If you have understood how the type checking is done for a variable understanding this will be very simple. Lets see how the types work in function.</p>
<h2 id="heading-parameter-type">Parameter type</h2>
<p>when you specify the parameter type typescript will warn you if you try to perform operation on that particular parameter which is outside the scope of its type. for example if you have specified the type as <strong>number</strong> and you are trying to apply <strong>string</strong> methods on the parameter you’ll get a red line.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712588886077/7ebc6c03-3dc8-42bc-ada7-463b468e56ed.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-return-type">Return type</h2>
<p>when return type of a function is specified, you can’t return a value from the function which is other than the specified type. for example you cant return a <strong>string</strong> if you have specified the return type as a <strong>number</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712588946200/76606426-44d9-4134-94dc-5f138418e37a.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-arrow-function-anatomy-for-typescript">Arrow Function Anatomy for TypeScript</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712589036511/63aff673-45d3-4a61-8d7f-3fafe6a76b96.png" alt class="image--center mx-auto" /></p>
<p>Every functionality remains the same expect the minor syntax changes</p>
<h2 id="heading-using-types-in-map-or-any-call-back-function">Using types in map or any call back function</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712589100518/e5b1b527-09d3-4fd2-8edc-964d8d557508.png" alt class="image--center mx-auto" /></p>
<p>it’s the same syntax we use for arrow function with only difference that the function is being placed inside another function.</p>
<p>actually it’s not required to specify the type when we are using the map function because <strong>TypeScript</strong> is smart enough to know the type value we’ll be having for the parameter by reading the <strong>array</strong> on which we are using the map.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712589198631/596bc124-bae0-4246-95b2-a1a6c62a1e7c.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1712589220346/1f2b8ad9-40e5-41b3-b3f6-6cf5c33c1e29.png" alt /></p>
<p>if you don’t specify the type and hover over the variable you can see that it already knows what type is it (I'm using VS code).</p>
<h2 id="heading-never-type">Never Type</h2>
<p>We use <strong>never</strong> when we want to specify that the function should not return anything not even void. This is helpful when we want to call the function which terminates our program or just raises and error.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">rainsError</span>(<span class="hljs-params">errMsg: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">never</span></span>{
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(errMsg);
}
</code></pre>
<p>if you reached till here and you liked what you read don't forget to share it with other people. if you have any feedback or suggestions feel free to use the comment section. Hope you tag along till the end of this series and strengthen your coding armor by adding <strong>TypeScript</strong> to it. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[TypeScript Unlocked: Types]]></title><description><![CDATA[💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.


What are t...]]></description><link>https://blog.troncodes.in/typescript-unlocked-types</link><guid isPermaLink="true">https://blog.troncodes.in/typescript-unlocked-types</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[coding]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[clean code]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Thu, 04 Apr 2024 09:38:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1712221933793/e016f5e2-a9df-4cc5-9df3-f9e538e71e7d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This article is a part of <a target="_blank" href="https://blog.troncodes.com/series/typescript-unlocked">TypeScript Unlocked</a> Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.</div>
</div>

<h2 id="heading-what-are-types">What are types?</h2>
<p>To understand Types we can take example of real world Caste System. In Caste system people are divided into different groups based on the work they do and they are treated differently based on their castes. I know its not fair but this is how it used to be in some parts of the world and this system is practiced even today in some rural parts of India and other 3rd world countries.</p>
<p>Just like the Caste system we have different types in Typescript and each type has its own property. Like Type of Number will only accept numbers type of String will only accept string and type of Boolean will only accepts Boolean and so on..</p>
<h2 id="heading-syntax">Syntax</h2>
<p>const <code>variableName</code> : <code>type</code> = <code>value</code></p>
<p><strong>Example</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> age : <span class="hljs-built_in">number</span> = <span class="hljs-number">24</span>
</code></pre>
<p>so this is how we define types for any <strong>variable</strong>. in this example we have used the <strong>number</strong> type which is used to represent a number obviously.</p>
<p>let's look at some of the basic types which we have in TypeScript.</p>
<ol>
<li><p><strong>Number:</strong></p>
<ul>
<li><p>Represents numeric values (integers or floating-point numbers).</p>
</li>
<li><p>Examples: <code>let count: number = 5;</code>, <code>let pi: number = 3.14;</code></p>
</li>
</ul>
</li>
<li><p><strong>String:</strong></p>
<ul>
<li><p>Represents textual data enclosed within single (<code>'</code>) or double (<code>"</code>) quotes.</p>
</li>
<li><p>Examples: <code>let message: string = 'Hello, TypeScript!';</code>, <code>let name: string = "Alice";</code></p>
</li>
</ul>
</li>
<li><p><strong>Boolean:</strong></p>
<ul>
<li><p>Represents logical values <code>true</code> or <code>false</code>.</p>
</li>
<li><p>Examples: <code>let isValid: boolean = true;</code>, <code>let hasError: boolean = false;</code></p>
</li>
</ul>
</li>
</ol>
<p>These 3 are primitive types in Plain JavaScript and has a corresponding type in TypeScript which we can use to do type Notations. There are variety of <strong>inbuild</strong> types and we can also create our own types. we'll Learn about this as we progress in the series.</p>
<p>There is one more important type</p>
<ol start="4">
<li><p><strong>Any</strong></p>
<ul>
<li><p>Any means we are telling TypeScript to not do any type checking of the the variable</p>
</li>
<li><p>Examples: <code>let car: any = "BMW";</code>, <code>let bike: any = 5;</code></p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-inferred-types">Inferred types</h2>
<p>TypeScript is smart enough to automatically assign the type to the variable looking at the value you have assigned to the variable.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> num : <span class="hljs-built_in">number</span> = <span class="hljs-number">5</span>
</code></pre>
<p>you can also write this as</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> num = <span class="hljs-number">5</span>
</code></pre>
<p>even though you have not mentioned the type, typescript will automatically assign one to it. In future if you try to assign a String or any other value to num TypeScript will warn you automatically.</p>
<p>In many cases its a good practice to rely on inferred types because its obvious of what <strong>type</strong> the <strong>variable</strong> should be by looking at the <strong>value</strong> but there are some exceptions where we should avoid using type inference.</p>
<p>So this post covers the crux of types we'll be looking at different types and how to use them in later as we go further into the series.</p>
<p>You can also checkout <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/2/everyday-types.html">TypeScript Docs</a> for more info on types.</p>
<p>if you reached till here and you liked what you read don't forget to share it with other people. if you have any feedback or suggestions feel free to use the comment section. Hope you tag along till the end of this series and strengthen your coding armor by adding <strong>TypeScript</strong> to it. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[TypeScript Unlocked: Introduction]]></title><description><![CDATA[💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.


Hey there,...]]></description><link>https://blog.troncodes.in/typescript-unlocked-introduction</link><guid isPermaLink="true">https://blog.troncodes.in/typescript-unlocked-introduction</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[coding]]></category><category><![CDATA[clean code]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Tue, 02 Apr 2024 11:27:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1712051473675/7dccedd2-81c0-42a7-be64-4cf0691437f2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This article is a part of <a target="_blank" href="https://blog.troncodes.com/series/typescript-unlocked">TypeScript Unlocked</a> Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.</div>
</div>

<p>Hey there, happy to have you here! In this section we will see what is <strong>TypeScript</strong>, why do we use it and bit of it's history. Don't worry I won't bore you much I'm just covering this so you get the context why was TypeScript introduced in the first place.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">You should have basic knowledge and understanding of how JavaScript works and function to continue with this series.</div>
</div>

<p>JavaScript by nature is loosely typed or <em>dynamic</em> programing language which means we don't have to explicitly specify types in <strong>JavaScript</strong> as we have to do it in statically typed languages like <strong>C, C++ or Java.</strong> let's see some example to understand it better.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> age = <span class="hljs-number">25</span>
age = <span class="hljs-string">"25"</span>
</code></pre>
<p>this code is invalid in <strong>C++</strong>, as its a statically typed language and we have specified <strong>age</strong> to be an integer so we can't assign a string value to <strong>age</strong>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age = <span class="hljs-number">25</span>
age = <span class="hljs-string">"25"</span>
</code></pre>
<p>the above code is valid in JavaScript because it's dynamically typed. first we set age as a number than we change it to a string value. <strong>JavaScript</strong> will internally handle the type change for us unlike <strong>C++</strong>.</p>
<p>I know this seems pretty convenient now but this behavior can lead to pretty nasty bugs if you don't be careful with it.</p>
<h2 id="heading-why-use-typescript">Why use TypeScript ?</h2>
<p>I'll really dumb down this example for understanding purpose. let's assume two or more people are working on a JavaScript code base and one person got a task to write a function to display age and he stored age as string for some reason.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age = <span class="hljs-number">25</span>
<span class="hljs-comment">// 1000 lines of code...</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayAge</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-comment">// lines of code...</span>
    age = <span class="hljs-string">"26"</span> + <span class="hljs-string">" yrs"</span>
    <span class="hljs-built_in">console</span>.log(age)
}
</code></pre>
<p>if he tests his function the above code will run fine without any errors. now let's say another person got a task to write a function to check if the <strong>user</strong> is eligible to vote.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age = <span class="hljs-number">25</span>
<span class="hljs-comment">// 100 lines of code...</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayAge</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-comment">// lines of code...</span>
    age = <span class="hljs-string">"26"</span> + <span class="hljs-string">" yrs"</span>
    <span class="hljs-built_in">console</span>.log(age)
}
<span class="hljs-comment">// 100 lines of code...</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isEligibleToVote</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-comment">// lines of code...</span>
    <span class="hljs-keyword">if</span> (age &gt; <span class="hljs-number">18</span>){
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
}
</code></pre>
<p>Now if he tested his function it will work fine but did you notice the problem here? Until <code>displayAge</code> function is called everything will run smoothly but if we run <code>isEligibleToVote</code> function after <code>displayAge</code> our code will raise an error and our application will crash because <strong>age</strong> is no longer a number and we can't compare a string with a number.</p>
<p>This is how <strong>dynamically</strong> typed languages are prone to bugs. The above example was very simple which would most likely not happen in real world production scenario but many more <strong>complex</strong> and <strong>unexpected</strong> bugs can arise in production if we don't be very very careful. This is where <strong>TypeScript</strong> comes into the picture to save the day.</p>
<h2 id="heading-what-is-typescript"><strong>What is Typescript?</strong></h2>
<p><strong>TypeScript</strong> was developed by <a target="_blank" href="https://en.wikipedia.org/wiki/Microsoft">Microsoft</a>, led by <a target="_blank" href="https://en.wikipedia.org/wiki/Anders_Hejlsberg"><strong>Anders Hejlsberg</strong></a>. It addresses issues in <strong>JavaScript</strong> development by adding <strong>static typing</strong>, enabling better code <strong>organization</strong>, <strong>scalability</strong>, and <strong>error detection</strong> during development.</p>
<p>For the people who don't know. <strong>TypeScript</strong> is not a new programming language, it's just some syntactical sugar on top of vanilla <strong>JavaScript</strong>. You can imagine it as a layer of syntax of top of normal <strong>JavaScript</strong> syntax. <strong>TypeScript</strong> is just an development tool which makes your life easier by making you write better code. Ultimately the <strong>TypeScript</strong> code you write will be compiled into <strong>JavaScript</strong> because the browser/node only understands <strong>JavaScript</strong>.</p>
<p>Now let's see how can typescript solve the issue we discussed in the above example.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> age: <span class="hljs-built_in">number</span> = <span class="hljs-number">25</span>
</code></pre>
<p>so when we are defining age we add a colon followed by <strong>number</strong> keyword which specifies that age should only contain a <strong>numeric</strong> value. Now whenever someone tries to store anything other than a <strong>number</strong> in age an error will get raised so future bugs can be prevented. This is one of the feature of <strong>TypeScript</strong> which helps us write a better quality code.</p>
<p>As we move on in the series we will see how you can install and use <strong>TypeScript</strong> in your codebases and we will discuss the following topics in detail.</p>
<ul>
<li><p><strong>Types</strong></p>
</li>
<li><p><strong>Functions</strong></p>
</li>
<li><p><strong>Type Aliases</strong></p>
</li>
<li><p><strong>Read-only, Optional and Type Mixing</strong></p>
</li>
<li><p><strong>Unions</strong></p>
</li>
<li><p><strong>Tuple</strong></p>
</li>
<li><p><strong>Interface</strong></p>
</li>
<li><p><strong>Public, Private and Protected</strong></p>
</li>
<li><p><strong>Getters and Setters</strong></p>
</li>
<li><p><strong>Abstract Classes</strong></p>
</li>
<li><p><strong>Generics</strong></p>
</li>
<li><p><strong>Narrowing</strong></p>
</li>
</ul>
<p>if you reached till here and you liked what you read don't forget to share it with other people. if you have any feedback or suggestions feel free to use the comment section. Hope you tag along till the end of this series and strengthen your coding armor by adding <strong>TypeScript</strong> to it. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[GitHub Pages for React: Vite Deployment and Custom Domain Configuration]]></title><description><![CDATA[There are two simple ways to deploy your react apps on GitHub Pages. The simple way is to use gh-pages package which does most of the work for you it handles all the configs and other details. Another way is the manual way where you do all the work b...]]></description><link>https://blog.troncodes.in/github-pages-for-react-vite-deployment-and-custom-domain-configuration</link><guid isPermaLink="true">https://blog.troncodes.in/github-pages-for-react-vite-deployment-and-custom-domain-configuration</guid><category><![CDATA[GitHub]]></category><category><![CDATA[vite]]></category><category><![CDATA[React]]></category><category><![CDATA[deployment]]></category><category><![CDATA[GitHubPages]]></category><category><![CDATA[domain]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Sat, 23 Dec 2023 11:27:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703330820300/7f4c1631-2ccd-46ca-9c3b-3d1adacc6c69.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>There are two simple ways to deploy your react apps on GitHub Pages. The simple way is to use <code>gh-pages</code> package which does most of the work for you it handles all the configs and other details. Another way is the manual way where you do all the work by yourself. for this post we’ll be seeing how to do it using <code>gh-pages</code></p>
<h2 id="heading-using-gh-pages">Using gh-pages</h2>
<h3 id="heading-install-the-package-on-your-local-dev-environment">Install the package on your local dev environment.</h3>
<pre><code class="lang-bash">yarn add -D gh-pages
</code></pre>
<p>you can also you other package manager such as NPM.</p>
<h3 id="heading-add-these-commands-under-scripts-in-packagejson">Add these commands under scripts in <code>package.json</code></h3>
<pre><code class="lang-bash"><span class="hljs-string">"scripts"</span>: {
        <span class="hljs-string">"predeploy"</span>: <span class="hljs-string">"yarn run build"</span>,
        <span class="hljs-string">"deploy"</span>: <span class="hljs-string">"gh-pages -d dist"</span>
  }
</code></pre>
<p>You can use npm or other equivalent commands related to different package managers</p>
<h3 id="heading-update-vitejsconfig">Update <code>vite.js.config</code></h3>
<ul>
<li><p>If you are deploying to <code>https://&lt;USERNAME&gt;.</code><a target="_blank" href="http://github.io/"><code>github.io/</code></a>, or to a custom domain through GitHub Pages (e.g. <a target="_blank" href="http://www.example.com"><code>www.example.com</code></a>), set <code>base</code> to <code>'/'</code>. Alternatively, you can remove <code>base</code> from the configuration, as it defaults to <code>'/'</code>.</p>
<pre><code class="lang-jsx">  <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
    <span class="hljs-attr">base</span>: <span class="hljs-string">"/"</span>,
    <span class="hljs-attr">plugins</span>: [react()],
  })
</code></pre>
</li>
<li><p>If you are deploying to <code>https://&lt;USERNAME&gt;.</code><a target="_blank" href="http://github.io/&lt;REPO&gt;/"><code>github.io/&lt;REPO&gt;/</code></a> (eg. your repository is at <a target="_blank" href="https://github.com/&lt;USERNAME&gt;/&lt;REPO&gt;"><code>https://github.com/&lt;USERNAME&gt;/&lt;REPO&gt;</code></a>), then set <code>base</code> to <code>'/&lt;REPO&gt;/'</code>.</p>
<pre><code class="lang-bash">  <span class="hljs-built_in">export</span> default defineConfig({
    base: <span class="hljs-string">"/portfolio-site/"</span>, // portfolio-site is the name of my repo
    plugins: [react()],
  })
</code></pre>
</li>
</ul>
<h3 id="heading-run-the-command-to-deploy">Run the command to deploy</h3>
<pre><code class="lang-bash">yarn run deploy
</code></pre>
<p>You can use npm or other equivalent commands related to different package managers. This command will build your project and create a new branch called <code>gh-pages</code> in your git repository and push it on GitHub and it will also handle the configuration required to deploy your project.</p>
<p>This is it! Congratulations🎉🎉🎉 your static site will be deployed, to check you can go to your repository’s setting and go in the pages section</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703327658735/0ee22923-51e9-4f57-8ef5-23c076211b76.png" alt class="image--center mx-auto" /></p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">check the <a target="_blank" class="notion-link-token notion-focusable-token notion-enable-hover" href="https://vitejs.dev/guide/static-deploy">Vite Docs</a> for more details</div>
</div>

<h2 id="heading-setting-custom-domain-for-your">Setting custom domain for your</h2>
<p>The first thing to do is buy a domain of you choice. you can buy it from <a target="_blank" href="https://www.godaddy.com/">GoDaddy</a> <a target="_blank" href="https://www.hostinger.in/">Hostinger</a> etc. It’s a very straight forward process you go to their site add domains to your cart and checkout just like any other ecommerce site.</p>
<p><strong>Now for GitHub pages we can set two types of domains</strong></p>
<ul>
<li><p><strong>Apex domain</strong></p>
<p>  e.g.: <a target="_blank" href="http://troncodes.com">troncodes.com</a></p>
</li>
<li><p><strong>Subdomain</strong></p>
<p>  e.g.: <a target="_blank" href="http://troncodes.com">www.troncodes.com</a> or <a target="_blank" href="http://troncodes.com">blog.troncodes.com</a></p>
</li>
</ul>
<p>To point your apex domain to your GitHub page simply go to your domain’s DNS settings on your domain provider’s site. if you can’t find it, a simple google search will help you figure it out. once you get into your domain’s DNS setting you will see a similar table to this.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703328063974/1a7433f4-036d-434c-becc-623b93e6189d.png" alt class="image--center mx-auto" /></p>
<p>But you will not have all these A records which you see in the above picture if you have not already set them. the IP’s which you see are of GitHub’s public servers which hosts your page. They are provided by GitHub.</p>
<pre><code class="lang-json"><span class="hljs-number">185.199</span><span class="hljs-number">.108</span><span class="hljs-number">.153</span>
<span class="hljs-number">185.199</span><span class="hljs-number">.109</span><span class="hljs-number">.153</span>
<span class="hljs-number">185.199</span><span class="hljs-number">.110</span><span class="hljs-number">.153</span>
<span class="hljs-number">185.199</span><span class="hljs-number">.111</span><span class="hljs-number">.153</span>
</code></pre>
<p>Add four <code>A</code> records as I have added above in your Domain’s DNS setting use the above mentioned IP’s and keep rest of the setting exactly as shown above. What this does is whenever any look up is done for your domain the request will be sent to GitHub’s servers which than will respond back with the content of your GitHub page.</p>
<p>Now the DNS servers knows to forward any requests looking up for your domain should be forwarded to GitHub but GitHub does not know what it should do with this request. So we need to configure that as well.</p>
<h3 id="heading-configuring-github-repo">Configuring GitHub Repo</h3>
<p>go to repository settings and navigate to pages just like before. scroll down to see and you’ll see a section for custom domain. Enter the name of your domain, save and you are done.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703328376452/1c7a5239-2183-430a-b87b-ce42c9aee5ad.png" alt class="image--center mx-auto" /></p>
<p>wait for some time and refresh the page. you’ll see a link which points to your website. Congratulations🎉🎉🎉 your website will now be displayed on your custom domain.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">if you want to know more details about it checkout <a target="_blank" class="notion-link-token notion-focusable-token notion-enable-hover" href="https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/managing-a-custom-domain-for-your-github-pages-site#configuring-an-apex-domain-and-the-www-subdomain-variant">GitHub Docs</a> for the same</div>
</div>

<h3 id="heading-setting-up-a-sub-domain">Setting up a sub domain</h3>
<p>GitHub recommends also setting up a <code>www</code> subdomain. If you configure the correct records for each domain type through your DNS provider, GitHub Pages will automatically create redirects between the domains. For example, if you configure <a target="_blank" href="http://www.example.com">www.example.com</a> as the custom domain for your site, and you have GitHub Pages DNS records set up for the apex and www domains, then <a target="_blank" href="http://example.com">example.com</a> will redirect to <a target="_blank" href="http://www.example.com">www.example.com</a>. Note that automatic redirects only apply to the <code>www</code> subdomain. Automatic redirects do not apply to any other subdomains, such as <code>blog</code></p>
<p>To set up a subdomain subdomain you just have to add a <code>C</code> record in your DNS setting with the following settings.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703328580628/252c5412-6917-40fc-b76f-4668ab3aa91d.png" alt class="image--center mx-auto" /></p>
<p><code>www</code> is value of your subdomain and this time instead of using IP’s we give this link yourUserName.<a target="_blank" href="http://github.io">github.io</a> that’s it. Don't forget to replace <code>yourUserName</code> with your own user name or organization name.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">if you want to know more details about it checkout <a target="_blank" class="notion-link-token notion-focusable-token notion-enable-hover" href="https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/managing-a-custom-domain-for-your-github-pages-site#configuring-an-apex-domain-and-the-www-subdomain-variant">GitHub Docs</a> for the same</div>
</div>]]></content:encoded></item><item><title><![CDATA[JSX exposed! What is JSX and how it works]]></title><description><![CDATA[What is JSX?
JSX stands for JavaScript syntax extension. It is a JavaScript extension that allows us to describe React’s object tree using a syntax that resembles that of an HTML template. It is just an XML-like extension that allows us to write Java...]]></description><link>https://blog.troncodes.in/jsx-exposed-what-is-jsx-and-how-it-works</link><guid isPermaLink="true">https://blog.troncodes.in/jsx-exposed-what-is-jsx-and-how-it-works</guid><category><![CDATA[React]]></category><category><![CDATA[JSX]]></category><category><![CDATA[js]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Thu, 07 Dec 2023 11:20:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/xkBaqlcqeb4/upload/fd1f220237c2f4071e73bc5ececf1967.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-what-is-jsx"><strong>What is JSX?</strong></h1>
<p>JSX stands for JavaScript syntax extension. It is a JavaScript extension that allows us to describe React’s object tree using a syntax that resembles that of an HTML template. It is just an XML-like extension that allows us to write JavaScript that looks like markup and have it returned from a component. Its just HTML disguised as JavaScript</p>
<pre><code class="lang-javascript"><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">let</span> name = <span class="hljs-string">"Palash"</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">h2</span>&gt;</span>Hello {name} Welcome to my Website<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
           <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is just a demo site<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">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>Everything which App function is returning is JSX. JSX looks like HTML but actually it we'll be transformed into JavaScript when its being compiled. JSX allows us to write HTML like code inside JS file and everything works without breaking. On line 2 we have defined a variable name and then we are using that name on line 5 inside HTML like syntax which will render the value of name inside h2.</p>
<p>So how does this work. How we can return HTML inside of JavaScript file directly?</p>
<h2 id="heading-jsx-under-the-hood"><strong>JSX UNDER THE HOOD</strong></h2>
<p>When we run our react application, react uses transpiler (a compiler that translates one form of syntax into another) called <a target="_blank" href="https://babeljs.io/">Babel</a> to transform JSX into plain JavaScript code which is understandable by the browser because the browser only understands JavaScript it does not understand what is JSX.</p>
<p>Let's see an example to understand it better</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <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">Greet</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<p>The above component is simple it will just render Hello World and it looks like it is returning <code>h1</code> tag but actually this code will be converted to JavaScript code by <strong><em>Babel</em></strong> before compiling and will look something like this.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <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">Greet</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> React.createElement(<span class="hljs-string">"h1"</span>, {}, <span class="hljs-string">"Hello, World!"</span>)
 }
</code></pre>
<p>HTML like code is being transformed into a JavaScript function call <strong><em>React.createElement()</em></strong>. This is the reason we need to import react in our file so it can be used later on to call this function.</p>
<h2 id="heading-working-of-reactcreateelement"><strong>Working of React.createElement</strong></h2>
<p>The createElement() function primarily accepts the following parameters and returns a React element(which is a JS object):</p>
<pre><code class="lang-javascript">React.createElement(
      type,
       [props], <span class="hljs-comment">//attribiute of the element</span>
      [...children]
    )
</code></pre>
<p>Let us see an example of how createElement function will be called, where we have attributes for the elements in JSX.</p>
<p><strong>JSX</strong></p>
<pre><code class="lang-javascript">&lt;div&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello JSX<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">label</span>=<span class="hljs-string">"screen"</span>&gt;</span>Sub heading<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span></span>
&lt;/div&gt;
</code></pre>
<p><strong>JavaScript</strong></p>
<pre><code class="lang-javascript">React.createElement(<span class="hljs-string">"div"</span>, {}, [
React.createElement(<span class="hljs-string">"h1"</span>, {}, <span class="hljs-string">"Hello JSX"</span>),
React.createElement(
        <span class="hljs-string">"h2"</span>,
        {
          <span class="hljs-attr">label</span>: <span class="hljs-string">"screen"</span>,
        },
        <span class="hljs-string">"Sub heading"</span>
        ),
        ]);
</code></pre>
<p>So this is how the actual JSX turns out when its pre-compiled by <strong><em>Babel.</em></strong></p>
<h3 id="heading-what-reactcreateelement-returns">What <strong>React.createElement()</strong> returns</h3>
<p><strong>Js file with JSX</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <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">App</span> (<span class="hljs-params"></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">p</span>&gt;</span>This is a list<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">li</span>&gt;</span>List item 1<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>List item 2<span class="hljs-tag">&lt;/<span class="hljs-name">li</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">div</span>&gt;</span></span>
       );
     };
</code></pre>
<p><strong>JavaScript after it has been compiled by <em>Babel</em></strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <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">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> React.createElement(
    <span class="hljs-string">"div"</span>,
    <span class="hljs-literal">null</span>,
    React.createElement(<span class="hljs-string">"p"</span>, <span class="hljs-literal">null</span>, <span class="hljs-string">"This is a list"</span>),
    React.createElement(
      <span class="hljs-string">"ul"</span>,
      <span class="hljs-literal">null</span>,
      React.createElement(<span class="hljs-string">"li"</span>, <span class="hljs-literal">null</span>, <span class="hljs-string">"List item 1"</span>),
      React.createElement(<span class="hljs-string">"li"</span>, <span class="hljs-literal">null</span>, <span class="hljs-string">"List item 2"</span>)
    )
  );
}
</code></pre>
<p>This is what <strong>React.createElement()</strong> will return</p>
<pre><code class="lang-javascript">    {
           <span class="hljs-string">"type"</span>: <span class="hljs-string">"div"</span>,
           <span class="hljs-string">"key"</span>: <span class="hljs-literal">null</span>,
           <span class="hljs-string">"ref"</span>: <span class="hljs-literal">null</span>,
           <span class="hljs-string">"props"</span>: {
             <span class="hljs-string">"children"</span>: [
               {
                 <span class="hljs-string">"type"</span>: <span class="hljs-string">"p"</span>,
                 <span class="hljs-string">"key"</span>: <span class="hljs-literal">null</span>,
                 <span class="hljs-string">"ref"</span>: <span class="hljs-literal">null</span>,
                 <span class="hljs-string">"props"</span>: {
                   <span class="hljs-string">"children"</span>: <span class="hljs-string">"This is a list"</span>
                 },
                 <span class="hljs-string">"_owner"</span>: <span class="hljs-literal">null</span>
               },
               {
                 <span class="hljs-string">"type"</span>: <span class="hljs-string">"ul"</span>,
                 <span class="hljs-string">"key"</span>: <span class="hljs-literal">null</span>,
                 <span class="hljs-string">"ref"</span>: <span class="hljs-literal">null</span>,
                 <span class="hljs-string">"props"</span>: {
                   <span class="hljs-string">"children"</span>: [
                     {
                       <span class="hljs-string">"type"</span>: <span class="hljs-string">"li"</span>,
                       <span class="hljs-string">"props"</span>: {
                         <span class="hljs-string">"children"</span>: <span class="hljs-string">"List item 1"</span>
                       },
                       <span class="hljs-comment">// truncated for brevity</span>
                     },
                     {
                       <span class="hljs-string">"type"</span>: <span class="hljs-string">"li"</span>,
                       <span class="hljs-string">"props"</span>: {
                         <span class="hljs-string">"children"</span>: <span class="hljs-string">"List item 2"</span>
                       },
                       <span class="hljs-comment">// truncated for brevity</span>
                     }
                   ]
                 },
                 <span class="hljs-string">"_owner"</span>: <span class="hljs-literal">null</span>
               }
             ]
           },
           <span class="hljs-string">"_owner"</span>: <span class="hljs-literal">null</span>
       }
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">There will be some other params included which will be internally used by react. This representation is just for understanding the workings</div>
</div>

<p>The actual one will look something like this.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1701944737244/e1fa7632-382b-4a05-b76f-a3955f0364e2.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-why-use-jsx">Why use JSX?</h2>
<p>Now that you understand how to use JSX and how it works. You may wonder why even use JSX why complicate things by adding code transpilers and everything why don't simply use plain HTML, CSS, JS.</p>
<p>Traditionally when we write code for a webpages, HTML CSS and JS are usually located in different files. Where HTML is used to render content CSS handles the styling part and JS handles the logic. But as your project grows bigger and things become more and more interactive. logic starts determining the content this is why in react rendering markup(HTML) and logic(JS) lives in the same place as a component and JSX makes this possible.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">To understand this better and in detail check out this <a target="_blank" href="https://react.dev/learn/writing-markup-with-jsx">Article</a></div>
</div>

<h2 id="heading-things-to-remember-when-using-jsx">Things to remember when using JSX</h2>
<ul>
<li><p>We can't return more than one element from a react component when using JSX. you can use react fragment to return multiple elements</p>
</li>
<li><p>Every tag should have a closing tag. Single tags like image tags can be return as <code>&lt;img/&gt;</code></p>
</li>
<li><p>Use camel case when writing HTML attribute names and change some names like class to <code>className</code> and for to <code>htmlFor</code></p>
</li>
</ul>
<p>That's it! with this knowledge you can get started with JSX and React. I hope you enjoyed reading this article and I made your react journey little bit simpler.</p>
]]></content:encoded></item><item><title><![CDATA[Setup and understand Apollo server in 10 mins]]></title><description><![CDATA[What is apollo server
Apollo Server is a community-driven, open-source GraphQL server that simplifies the process of building and serving GraphQL APIs in JavaScript environments. It's often used with Node.js, but it can also be used with other JavaSc...]]></description><link>https://blog.troncodes.in/setup-and-understand-apollo-server-in-10-mins</link><guid isPermaLink="true">https://blog.troncodes.in/setup-and-understand-apollo-server-in-10-mins</guid><category><![CDATA[Apollo GraphQL]]></category><category><![CDATA[GraphQL]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Query]]></category><category><![CDATA[GraphQL ]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Tue, 21 Nov 2023 11:16:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700564899316/c0040d92-b10d-4c3c-9586-9a6bd50a11b1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-apollo-server">What is apollo server</h2>
<p><strong>Apollo Server</strong> is a community-driven, open-source GraphQL server that simplifies the process of building and serving GraphQL APIs in JavaScript environments. It's often used with Node.js, but it can also be used with other JavaScript runtime environments. Apollo Server is part of the larger Apollo platform, which includes tools for both server and client development.</p>
<h2 id="heading-installation">Installation</h2>
<p>google “<strong>apollo GraphQL</strong>” and open the website. Navigate to developers → docs or simply open this link <a target="_blank" href="https://www.apollographql.com/docs/">https://www.apollographql.com/docs/</a></p>
<p>and scroll down to this section and read few things along the way if you want to.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700560486540/1baf5168-3f93-4ded-b601-b4e492110f60.png" alt class="image--center mx-auto" /></p>
<p>than click on the highlighted part and which will take you to the following page. this has information on how to install the server</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700560692693/6b291e7e-e5d0-48a5-b436-0740c68deea5.png" alt class="image--center mx-auto" /></p>
<p>or you can visit this page directly <a target="_blank" href="https://www.apollographql.com/docs/apollo-server/getting-started">Link</a></p>
<h2 id="heading-setting-up-the-server">Setting up the Server</h2>
<p>create a folder called <strong>server</strong> navigate inside the folder and run the following commands:</p>
<p>use this command to install apollo server and GraphQL</p>
<pre><code class="lang-bash">yarn add @apollo/server graphql
</code></pre>
<pre><code class="lang-bash">npm install @apollo/server graphql
</code></pre>
<p>add body parser, cors, axios, @type/axios as well to your project</p>
<pre><code class="lang-bash">yarn add body-parser cors axios @<span class="hljs-built_in">type</span>/axios
</code></pre>
<pre><code class="lang-bash">npm install body-parser cors axios @types/axios
</code></pre>
<h3 id="heading-body-parser">body-parser</h3>
<ul>
<li><p><strong>Role</strong>: <code>body-parser</code> is a middleware used in Express.js (a popular Node.js web framework) for parsing incoming request bodies.</p>
</li>
<li><p><strong>Context with GraphQL</strong>: In a GraphQL server, <code>body-parser</code> is often used to parse incoming HTTP POST requests containing GraphQL queries and mutations in the request body. It's responsible for extracting the JSON payload from the request body so that the GraphQL server can process the query.</p>
</li>
</ul>
<h3 id="heading-axios">axios</h3>
<ul>
<li><p><strong>Role</strong>: <code>axios</code> is a popular JavaScript library for making HTTP requests, both in the browser and on the server-side. It provides a convenient way to send HTTP requests and handle responses.</p>
</li>
<li><p><strong>Context with GraphQL</strong>: In the context of GraphQL, <code>axios</code> can be used in client-side applications to send GraphQL queries and mutations to a GraphQL server over HTTP. It can also be used to handle responses and manage GraphQL API interactions.</p>
</li>
</ul>
<h3 id="heading-cors-cross-origin-resource-sharing">CORS (Cross-Origin Resource Sharing)</h3>
<ul>
<li><p><strong>Role</strong>: <code>CORS</code> is a security feature implemented by web browsers that controls and manages cross-origin requests. It defines how a web server can allow or restrict access to its resources by web pages from other domains.</p>
</li>
<li><p><strong>Context with Web Development</strong>: In the context of web development, <code>CORS</code> plays a crucial role in enhancing security by preventing unauthorized access to resources from different origins (domains). It permits or restricts cross-origin HTTP requests made by client-side scripts in web applications.</p>
</li>
</ul>
<h2 id="heading-usage">Usage</h2>
<p>create a filed called <code>index.js</code> and import the following modules</p>
<pre><code class="lang-javascript"><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> {expressMiddleware} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'@apollo/server/express4'</span>)
<span class="hljs-keyword">const</span> {ApolloServer} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'@apollo/server'</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> cors = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cors'</span>)
<span class="hljs-keyword">const</span> { <span class="hljs-attr">default</span>: axios } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'axios'</span>)
</code></pre>
<p>Next we’ll create an async function named <strong>startServer</strong> which will have all the code to start and configure our server</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">startServer</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> app = express()
    <span class="hljs-keyword">const</span> server = <span class="hljs-keyword">new</span> ApolloServer({})
    <span class="hljs-keyword">const</span> port = <span class="hljs-number">8000</span>
    <span class="hljs-comment">// using middle ware</span>
    app.use(bodyParser.json())
    app.use(cors())

    <span class="hljs-keyword">await</span> server.start()

    app.use(<span class="hljs-string">"/graphql"</span>, expressMiddleware(server))
    app.listen(port,<span class="hljs-function">()=&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"server started on "</span> + port))
}
startServer()
</code></pre>
<p>in the above code we initialize express and apollo server. Set body parser and cors as middleware and start the server. Finally we tell express if any request comes on <code>/graphql</code> we serve it by using apollo server and we start listening on desired port. what this will do is whenever we enter <a target="_blank" href="http://localhost:8000">localhost:8000</a> on our browser we’ll get the apollo server UI and we can make use of its functionalities.</p>
<p>But if you run this code now it <strong>WON’T WORK</strong> and you’ll get an error. which says</p>
<blockquote>
<p><strong>Error: Query root type must be provided.</strong></p>
</blockquote>
<p>there are two more important concepts used when dealing with GraphQL.</p>
<ul>
<li><p><strong>type definitions</strong></p>
</li>
<li><p><strong>resolvers</strong></p>
</li>
</ul>
<p>In GraphQL, both type definitions (often referred to as "typeDefs") and resolvers are key components that define the structure and behavior of a GraphQL API. They are used to specify the schema and how data is fetched and manipulated. Let's dive into each of these components:</p>
<h1 id="heading-type-definitions-typedefs"><strong>Type Definitions (typeDefs):</strong></h1>
<p>Type definitions, or "typeDefs" define the <strong>structure</strong> and <strong>shape</strong> of the GraphQL schema. They specify the types of data that can be queried and mutated in your GraphQL API. Type definitions are typically written in the GraphQL Schema Definition Language (SDL), which is a human-readable way to define types, queries, mutations, and relationships.</p>
<p>Here's a basic example of type definitions for a simple GraphQL schema:</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">type</span> Query {
  <span class="hljs-symbol">hello:</span> String
  getUser(<span class="hljs-symbol">id:</span> ID!): User
}

<span class="hljs-keyword">type</span> User {
  <span class="hljs-symbol">id:</span> ID
  <span class="hljs-symbol">username:</span> String
  <span class="hljs-symbol">email:</span> String
}
</code></pre>
<p>In this example:</p>
<ul>
<li><p>We define a <code>Query</code> type with two fields: <code>hello</code> and <code>getUser</code>.</p>
</li>
<li><p>The <code>User</code> type has three fields: <code>id</code>, <code>username</code>, and <code>email</code>.</p>
</li>
</ul>
<p>Type definitions provide the structure for the available data in your GraphQL API. They serve as the contract between the client and server, outlining what data can be requested. we’ll see later how can we request data from the apollo server UI.</p>
<h1 id="heading-resolvers"><strong>Resolvers</strong></h1>
<p>Resolvers are JavaScript functions that define how to retrieve or manipulate the data for the fields defined in the type definitions. Each field in the type definitions corresponds to a resolver function. Resolvers are organized by the types they resolve, and they return the actual data when queried.</p>
<p>Here's an example of resolvers for the type definitions mentioned earlier:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> resolvers = {
  <span class="hljs-attr">Query</span>: {
    <span class="hljs-attr">hello</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-string">'Hello, world!'</span>,
    <span class="hljs-attr">getUser</span>: <span class="hljs-function">(<span class="hljs-params">parent, args</span>) =&gt;</span> {
      <span class="hljs-comment">// In a real application, you might fetch the user data from a database or another source</span>
      <span class="hljs-keyword">const</span> { id } = args;
      <span class="hljs-keyword">return</span> fetchUserDataById(id);
    },
  },
  <span class="hljs-attr">User</span>: {
    <span class="hljs-attr">id</span>: <span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> user.id,
    <span class="hljs-attr">username</span>: <span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> user.username,
    <span class="hljs-attr">email</span>: <span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> user.email,
  },
};
</code></pre>
<p>In this example:</p>
<ul>
<li><p>The <code>hello</code> field in the <code>Query</code> type is resolved by a function that returns the string <code>'Hello, world!'</code>.</p>
</li>
<li><p>The <code>getUser</code> field in the <code>Query</code> type is resolved with a function that takes an <code>id</code> argument and fetches user data by that ID from a data source (e.g., a database).</p>
</li>
</ul>
<p>Resolvers are crucial for defining how data is fetched, transformed, or computed. They connect your GraphQL schema to the actual data sources and services.</p>
<p>Together, type definitions and resolvers form the backbone of a GraphQL API. The type definitions define the available data and operations, while the resolvers determine how that data is fetched and presented to the client. This clear separation of concerns and self-documenting schema makes GraphQL powerful and flexible for building APIs.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">this examples are for understanding purposes. We’ll see how we can use apollo server UI interface to send request to our server and how typeDefs and resolvers work together to serve data</div>
</div>

<p>Now that you have good understanding of how type Definitions and Resolvers work, we’ll fix the error which we were getting earlier by entering these two things i our code (index.js).</p>
<pre><code class="lang-javascript"><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> {expressMiddleware} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'@apollo/server/express4'</span>)
<span class="hljs-keyword">const</span> {ApolloServer} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'@apollo/server'</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> cors = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cors'</span>)
<span class="hljs-keyword">const</span> { <span class="hljs-attr">default</span>: axios } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'axios'</span>)

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">startServer</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> app = express()
    <span class="hljs-keyword">const</span> server = <span class="hljs-keyword">new</span> ApolloServer({
       <span class="hljs-attr">typeDefs</span>:<span class="hljs-string">`
       type Todo {
            id: ID!
            title: String!
            completed: Boolean
            userId: ID!
            user: User
       }

       type User {
        id: ID!
        name: String!
        username: String!
        email: String!
        phone: String!
        website: String!
       }

       type Query {
            getTodos: [Todo]
            getAllUsers: [User]
            getUser(id:ID): User
       }
       `</span> ,
       <span class="hljs-attr">resolvers</span>: {
        <span class="hljs-comment">// todo is the parent which graph QL passes to the function by default</span>
        <span class="hljs-attr">Todo</span>:{
            <span class="hljs-attr">user</span>: <span class="hljs-keyword">async</span> (todo) =&gt; (<span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">`https://jsonplaceholder.typicode.com/users/<span class="hljs-subst">${todo.userId}</span>`</span>)).data
        },
        <span class="hljs-attr">Query</span>: {
            <span class="hljs-attr">getTodos</span>: <span class="hljs-keyword">async</span> () =&gt; (<span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos'</span>)).data,
            <span class="hljs-attr">getAllUsers</span>: <span class="hljs-keyword">async</span> () =&gt; (<span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users'</span>)).data,
            <span class="hljs-attr">getUser</span>: <span class="hljs-keyword">async</span> (parent, {id}) =&gt; (<span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">`https://jsonplaceholder.typicode.com/users/<span class="hljs-subst">${id}</span>`</span>)).data,
        }
       }
    })
    <span class="hljs-keyword">const</span> port = <span class="hljs-number">8000</span>
    <span class="hljs-comment">// using middle ware</span>
    app.use(bodyParser.json())
    app.use(cors())

    <span class="hljs-keyword">await</span> server.start()

    app.use(<span class="hljs-string">"/graphql"</span>, expressMiddleware(server))
    app.listen(port,<span class="hljs-function">()=&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"server started on "</span> + port))
}

startServer()
</code></pre>
<p>As you can see in the above code type definitions and resolvers go inside an object which is passed to Apollo Server instance. we area also using axios here to fetch data from an free API. This is the complete code you need to run apollo server using GraphQL.</p>
<h2 id="heading-requesting-data">Requesting data</h2>
<p>We just saw how we can configure the server using type definitions and resolvers to serve the data but we haven’t seen yet how the you can request data. GraphQL has an API using which we can send GraphQL queries and request for data. In this post we'll see how to send request to Apollo server using Apollo UI for testing the API.</p>
<h2 id="heading-graphql-query">GraphQL query</h2>
<p>In GraphQL, a query is a request made by a client to retrieve specific data from a GraphQL API. Queries are one of the fundamental building blocks of GraphQL and serve as a way for clients to specify exactly what data they need, and in what shape, from the API. Here are the key characteristics of GraphQL queries:</p>
<ol>
<li><p><strong>Structured Data Retrieval:</strong> In GraphQL, a query is a structured request for data. It allows clients to specify the fields and relationships they want to retrieve, making it highly efficient for data retrieval.</p>
</li>
<li><p><strong>Declarative Syntax:</strong> GraphQL queries are written in a declarative syntax, where clients declare what they want, and the server responds with exactly that data, and nothing more.</p>
</li>
<li><p><strong>Hierarchical Structure:</strong> Queries have a hierarchical structure, mirroring the shape of the data that's returned. Clients can request nested data structures to retrieve related data efficiently.</p>
</li>
<li><p><strong>Strongly Typed:</strong> GraphQL is a strongly typed query language. It requires the client to specify the types and fields they want to query, and it enforces a strict schema that defines what is available for retrieval.</p>
</li>
<li><p><strong>Single Request:</strong> Unlike traditional REST APIs that might require multiple requests to different endpoints to assemble the required data, GraphQL typically requires a single request to retrieve all the requested data.</p>
</li>
<li><p><strong>No Over-fetching or Under-fetching:</strong> With GraphQL queries, clients can avoid over-fetching (retrieving more data than needed) and under-fetching (making multiple requests for related data) issues, optimizing data transfer.</p>
</li>
</ol>
<p>Here's an example of a simple GraphQL query:</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">query</span> Query{
  user(<span class="hljs-symbol">id:</span> <span class="hljs-number">123</span>) {
    name
    email
    posts {
      title
      body
    }
  }
}
</code></pre>
<p>Breaking down the query:</p>
<ul>
<li><p><code>query</code> is the keyword that signals the beginning of a query operation.</p>
</li>
<li><p><code>user(id: 123)</code> is a field that represents a user query with an <code>id</code> argument.</p>
</li>
<li><p><code>name</code> and <code>email</code> are fields on the <code>user</code> object, specifying the data the client wants to retrieve about the user.</p>
</li>
<li><p><code>posts</code> is a field that represents a query for the user's posts.</p>
</li>
<li><p><code>title</code> and <code>body</code> are fields on the <code>posts</code> object, specifying the data the client wants to retrieve about each post.</p>
</li>
</ul>
<p>The response to this query will be structured in the same hierarchical way as the query, providing the requested user data and their posts with the specified fields.</p>
<p>GraphQL queries allow clients to be very precise in requesting the data they need, reducing over-fetching and minimizing the number of API requests. This flexibility and efficiency are some of the key advantages of GraphQL over traditional REST APIs.</p>
<p>So now we understand how GraphQL works at the server side and client side. we know how a GraphQL query can be structured and sent to the server. So now we’ll see some examples of how this works using apollo UI</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">GraphQL queries which we will be using now we’ll be sent to the server which has the code of index.js file which I have mentioned above. You can observe the queries and responses you get in the apollo UI and see how it corelates to the typeDefs and resolvers (please check responses of the APIs used in resolvers) and also how you can leverage the power of GraphQL</div>
</div>

<h2 id="heading-examples">Examples</h2>
<h3 id="heading-simple-query">simple query</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700563518748/9181224b-f1be-46eb-ac77-8e72aa375a31.png" alt class="image--center mx-auto" /></p>
<p>here you can see the apollo UI which lets us test our API. You can see in the operations tab we have entered our query and to our right is the response tab. lets look at the query now.</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">query</span> Query{
  getTodos {
    id
    title
  }
}
</code></pre>
<ol>
<li><p>on line one first we have entered the keyword query followed by ‘Query’ this is just a name which i choose you can replace it with anything else. This is the main block inside which we can specify our queries</p>
</li>
<li><p>on line 2 we type getTodos. this cannot be named as we like because we have specified this type in our TypeDefs and also we have specified a resolver for this. Whatever key/type we put inside the main block should be present inside the <strong>Query</strong> <strong>root</strong> on the server side.</p>
<p> <strong>TypeDefs</strong> at server</p>
<pre><code class="lang-javascript"> typeDefs:<span class="hljs-string">`
        type Todo {
             id: ID!
             title: String!
             completed: Boolean
             userId: ID!
             user: User
        }

        type User {
         id: ID!
         name: String!
         username: String!
         email: String!
         phone: String!
         website: String!
        }

        type Query {
             getTodos: [Todo]
             getAllUsers: [User]
             getUser(id:ID): User
        }
        `</span> ,
</code></pre>
<p> Here we can see that we have mentioned <strong>getTodos</strong> in the Query root and its suppose to return a list of <strong>Todos.</strong> Now look at the type for Todos and we can see that it can return <code>id</code>, <code>title</code>, <code>completed</code>, <code>userId</code>, <code>user</code></p>
<ol>
<li><p>So let us look back at the query. in the query we can see that inside getTodos we are specifying the id and title. So we are telling GraphQL for every todo we want only Id and title nothing else and if you look at the response you can see that we have gotten exactly what we have asked for</p>
</li>
<li><p>This shows how GraphQL only sends what we have asked for.</p>
</li>
</ol>
</li>
</ol>
<h2 id="heading-multiple-queries">Multiple queries</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700563918919/3517fe54-d2ea-4e1c-8c9f-49f27c0a9b04.png" alt class="image--center mx-auto" /></p>
<ol>
<li><p>Here we have also added <strong>getUser</strong> type and as you can observer we are getting list of <strong>Todos</strong> as well as response for <strong>getUser</strong>.</p>
</li>
<li><p>You may also observe that there is id passed to get user that is because the get user resolver is defined in such a way that it takes an argument. you can look into index.js file</p>
</li>
<li><p>So we can see that in single request we can fetch data from two different places</p>
</li>
</ol>
<h2 id="heading-given-arguments-through-variables">Given arguments through variables</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700564121394/afd8589a-8002-4b5b-9abd-58c27c5f4736.png" alt class="image--center mx-auto" /></p>
<ol>
<li>sometimes you may want to pass the value to a type through a variable and not hard code the value directly into the query.</li>
</ol>
<p>you can use the below syntax to pass the value as a variable</p>
<pre><code class="lang-graphql"><span class="hljs-keyword">query</span> Query(<span class="hljs-variable">$getUserId</span>: ID) {
  getUser(<span class="hljs-symbol">id:</span> <span class="hljs-variable">$getUserId</span>) {
    id
    email
  }
}
</code></pre>
<h2 id="heading-nested-queries">Nested Queries</h2>
<p>sometimes we may want to nest queries and access the value of the nested object(type).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700564231643/bc11debc-46b5-4c15-b650-5351f8326b27.png" alt class="image--center mx-auto" /></p>
<ol>
<li><p>here we are fetching the all the <strong>Todos</strong> using <strong>getTodos</strong> and accessing the user type for each todo which which will be returned by getTodos. please check the resolver definition inside the code of <strong>index.js</strong> to check how its done.</p>
</li>
<li><p>This is how we can make nested queries and get all the required info in single request to the server</p>
</li>
</ol>
<p>So this is it!! These are all the things you need to get started with GraphQL and understand how it works. I know its a long and detailed post and it took me a while to finish it. Soon I'll be posting a new blog explaining how to use GraphQL in Front end to so you can make queries programmatically. Hope you liked this post and it added some value to your coding journey. See you in the next one!</p>
]]></content:encoded></item><item><title><![CDATA[Cool looking counter in plain HTML,CSS and JS]]></title><description><![CDATA[We need a counter for a lot of stuff when building web apps whether be it displaying the number of users who visited our site, live views or any other stats. We can easily make one by simply using JS to manipulate the text inside an element that hold...]]></description><link>https://blog.troncodes.in/cool-looking-counter-in-plain-htmlcss-and-js</link><guid isPermaLink="true">https://blog.troncodes.in/cool-looking-counter-in-plain-htmlcss-and-js</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[HTML]]></category><category><![CDATA[CSS]]></category><category><![CDATA[animation]]></category><category><![CDATA[#counterapp]]></category><dc:creator><![CDATA[Palash Dhavle]]></dc:creator><pubDate>Wed, 13 Sep 2023 10:20:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1694541341604/6d796727-b17d-4d30-b2d0-da9785a836a2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We need a counter for a lot of stuff when building web apps whether be it displaying the number of users who visited our site, live views or any other stats. We can easily make one by simply using JS to manipulate the text inside an element that holds the value for the counter but it looks boring.</p>
<p>Now we'll see how can we make a better version of the counter which works like an odometer just using some plain HTML, CSS and JS.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>Note to Readers:</strong> This article is written with the assumption that you have a basic understanding of HTML, CSS, and JavaScript. We won't cover the fundamentals of these technologies in detail. If you are new to web development or need a refresher on these topics, consider exploring introductory tutorials and resources before diving into this content. although I can assure you I tried to keep it as simple as possible</div>
</div>

<h2 id="heading-what-the-final-result-looks-like">What the final result looks like</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694541450976/20639d44-54ab-48ae-9928-6844f26b4bf2.gif" alt="Final result gif" class="image--center mx-auto" /></p>
<h2 id="heading-html">HTML</h2>
<p>First, we will set up a basic HTML structure, I have also added some CSS classes to the elements which we'll see later in the CSS part. We'll name the file index.html</p>
<pre><code class="lang-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> <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>Counter<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">"box"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"counter-container"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"cc"</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">"button-container"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"bc"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"button red"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"backword"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"b"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"button green"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"forward"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"f"</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">"counter_script.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 three things(div) to consider here</p>
<ul>
<li><p><strong>box</strong> - div with a class box that holds two other divs counter-container and button-container</p>
</li>
<li><p><strong>Counter-container</strong> - This will be populated using JavaScript later. This will hold the contents of the counter</p>
</li>
<li><p><strong>button container</strong> - This will hold the buttons used to increase and decrease the counter</p>
</li>
</ul>
<p>I have also linked a stylesheet and a script to this document which I'll explain later</p>
<h2 id="heading-css">CSS</h2>
<p>Let's make things look pretty</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span>,<span class="hljs-selector-tag">html</span>{
    <span class="hljs-attribute">height</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">overflow</span>: hidden;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0px</span>;
}

<span class="hljs-selector-class">.box</span>{
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">50</span>, <span class="hljs-number">49</span>, <span class="hljs-number">48</span>);
    <span class="hljs-attribute">justify-content</span>: center;
    <span class="hljs-attribute">align-items</span>: center;
    <span class="hljs-attribute">flex-direction</span>: column;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">100%</span>;
}

<span class="hljs-selector-class">.counter-container</span>{
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">width</span>: fit-content;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">4px</span> <span class="hljs-built_in">rgb</span>(<span class="hljs-number">73</span>, <span class="hljs-number">71</span>, <span class="hljs-number">66</span>) solid;
    <span class="hljs-attribute">overflow</span>: hidden;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">10px</span>;
}

<span class="hljs-selector-class">.button-container</span>{
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">171</span>, <span class="hljs-number">166</span>, <span class="hljs-number">159</span>);
}

<span class="hljs-selector-class">.button</span>{
    <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Consolas'</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">15px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">80px</span>;
}

<span class="hljs-selector-class">.green</span>{
    <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">159</span>, <span class="hljs-number">227</span>, <span class="hljs-number">159</span>);
}

<span class="hljs-selector-class">.red</span>{
    <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">227</span>, <span class="hljs-number">136</span>, <span class="hljs-number">111</span>);
}

<span class="hljs-selector-class">.outer-container</span>{
    <span class="hljs-attribute">background-color</span>:<span class="hljs-built_in">rgb</span>(<span class="hljs-number">189</span>, <span class="hljs-number">200</span>, <span class="hljs-number">201</span>);
    <span class="hljs-attribute">padding-left</span>: <span class="hljs-number">4px</span>;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">70px</span>;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> black solid;
}

<span class="hljs-selector-class">.number-container</span>{
    <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Consolas'</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">60px</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">0.6em</span>;
    <span class="hljs-attribute">transition</span>: transform;
    <span class="hljs-attribute">transition-duration</span>: <span class="hljs-number">0.2s</span>;
}

<span class="hljs-selector-class">.number</span>{
    <span class="hljs-attribute">height</span>: <span class="hljs-number">70px</span>;
}
</code></pre>
<p>Here we can see all the definitions of CSS classes that we have used in our HTML. I'll explain this CSS in a brief</p>
<ul>
<li><p>box - this will be applied to the outermost box and we want its content to be at the center of the screen.</p>
</li>
<li><p>counter-container - This will be applied to the div/container of the counter and its overflow is hidden for a reason which I'll explain later</p>
</li>
<li><p>button-container - This will be applied to the div/container that holds the buttons</p>
</li>
<li><p>green, red - these are just class</p>
</li>
<li><p>body, html - we set the height of this element to 100% so the whole screen is covered</p>
</li>
<li><p>outer-container - This will be applied to the div that holds the divs representing each digit of the number. This div will be later added to the DOM using JS</p>
</li>
<li><p>number-container - This will be applied to individual digit divs that will hold the divs of numbers ranging from 0 to 9. This div will be later added to the DOM using JS</p>
</li>
<li><p>number - this will be applied to the div that holds each number</p>
</li>
</ul>
<p>Don't worry if you find this a little bit confusing you'll understand this later when we talk counter container will be populated using JavaScript</p>
<blockquote>
<p>The only thing you need to keep in mind while styling this is the overflow of the counter-container should be hidden as this directly affects the look and functionality of the counter. You need to also maintain the HTML structure as shown above for this to work</p>
</blockquote>
<h2 id="heading-javascript">JavaScript</h2>
<p>I will be explaining this JS code function by function first. Once we know the purpose of each function we will see how we use the functions to get our desired result.</p>
<p>We have three functions</p>
<ul>
<li><p>get_number_digits</p>
</li>
<li><p>make_number_containers</p>
</li>
<li><p>counter_setter</p>
</li>
</ul>
<p><strong>get_number_digits</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get_number_digits</span>(<span class="hljs-params">number</span>)</span>{
    <span class="hljs-keyword">if</span> (number == <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>

    <span class="hljs-keyword">let</span> number_of_digits = <span class="hljs-number">0</span>
    <span class="hljs-keyword">while</span>(number &gt; <span class="hljs-number">0</span>) {
        number = <span class="hljs-built_in">Math</span>.floor(number/<span class="hljs-number">10</span>)
        number_of_digits ++
    }
    <span class="hljs-keyword">return</span> number_of_digits
}
</code></pre>
<p>This function will return the number of digits in a given number for example if the number is 3432 number of digits will be 4. If the number is 23932 the number of digits will be 5.</p>
<p><strong>make_number_containers</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">make_number_containers</span>(<span class="hljs-params">number_of_digits</span>) </span>{
    <span class="hljs-keyword">let</span> counter_c = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'cc'</span>)

    <span class="hljs-comment">// creating a number container for each digit of the number</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> index = number_of_digits; index &gt; <span class="hljs-number">0</span>; index--) {

        <span class="hljs-comment">// creating outer container and adding the required class</span>
        <span class="hljs-keyword">let</span> outer_c = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>)
        outer_c.classList.add(<span class="hljs-string">'outer-container'</span>)

        <span class="hljs-comment">// creating number container and adding the required class and id</span>
        <span class="hljs-keyword">let</span> num_c = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"div"</span>)
        num_c.classList.add(<span class="hljs-string">'number-container'</span>)
        num_c.id = <span class="hljs-string">'nums'</span> + index

        <span class="hljs-comment">// adding number div inside number container. one for each from 0-9</span>
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) {
            <span class="hljs-keyword">let</span> num = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>)
            num.classList.add(<span class="hljs-string">'number'</span>)
            num.innerText = i
            num_c.appendChild(num)
        }

        outer_c.appendChild(num_c)
        counter_c.appendChild(outer_c)
    }

}
</code></pre>
<p>The idea behind this function is that we create an outer-container for each digit of a number inside the counter. Inside it, we create a number-container that has 10 divs. Each div will represent a number from 0-9.</p>
<p>You will understand it better when you see this picture.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694544760236/76713d70-53b7-427c-be57-0526edfc1828.png" alt class="image--center mx-auto" /></p>
<p>Let us assume the number is 0 so the number of digits will be 1 in that case only one container will be created. For the demonstration purpose, I have <strong>removed</strong> the <strong><em>overflow: hidden</em></strong> property of the <strong>counter-container</strong> class. This will give you a better perspective of things and now you will also understand the purpose of making the overflow hidden of counter-container.</p>
<p>HTML for the above image will look like this</p>
<pre><code class="lang-xml"><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>Counter<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">"box"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"counter-container"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"cc"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"outer-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">"number-container"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"nums1"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"transform: translateY(0px);"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"number"</span>&gt;</span>0<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">"number"</span>&gt;</span>1<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">"number"</span>&gt;</span>2<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">"number"</span>&gt;</span>3<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">"number"</span>&gt;</span>4<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">"number"</span>&gt;</span>5<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">"number"</span>&gt;</span>6<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">"number"</span>&gt;</span>7<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">"number"</span>&gt;</span>8<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">"number"</span>&gt;</span>9<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>&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">"counter_script.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 we have only one digit so only one container is created. If we set the <strong><em>overflow: hidden</em></strong> property of the <strong>counter-container</strong> class as intended we will get the following result</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694589760817/2462ad66-da80-43ee-8644-734c73fe5a0e.png" alt class="image--center mx-auto" /></p>
<p><strong>counter_setter</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter_setter</span>(<span class="hljs-params">number,salt</span>) </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> index = <span class="hljs-number">1</span>; index &lt;= number_of_digits; index++) {
        <span class="hljs-comment">// getting the correct number container</span>
        <span class="hljs-keyword">let</span> id = <span class="hljs-string">'nums'</span> + index
        <span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.getElementById(id)

        <span class="hljs-comment">// Geting the last digit of number</span>
        <span class="hljs-keyword">const</span> digit = (number % <span class="hljs-number">10</span>); 
        <span class="hljs-keyword">let</span> value = <span class="hljs-built_in">Math</span>.floor(SLIDE_CONST * digit)
        value = <span class="hljs-built_in">Math</span>.round(value + (salt * digit)) <span class="hljs-comment">// adding salt to the value</span>

        <span class="hljs-comment">// updating the translate value of the div after 200ms</span>
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> { div.style.transform = <span class="hljs-string">`translateY(-<span class="hljs-subst">${value}</span>px)`</span> }, <span class="hljs-number">200</span>)
        number = <span class="hljs-built_in">Math</span>.floor(number / <span class="hljs-number">10</span>); <span class="hljs-comment">// Remove the last digit</span>
    }
}
</code></pre>
<p>Now we have a better picture of how the number divs are stacked on top of each other and because the overflow is hidden we can only see one number at a time. Now to display any number we just have to slide the number container up or down.</p>
<p>We calculate the number of pixels we need to slide the number container using this simple formula</p>
<blockquote>
<p>silde_value = slide_constant x digit</p>
</blockquote>
<p>where slide constant is the height of the div containing each number. In our case height is <strong>70px</strong>. Suppose we have to display the number <strong>7</strong>. Using the above formula we have to slide the container that holds the stacked divs of number exactly <strong>490px.</strong></p>
<p>The basic idea of this function is that we simply go through each digit of the given number access its number container and slide it depending on the value of the digit</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The salt variable in the function is added because sometimes due to sub-pixel rendering and some other factors even when we calculate the sliding value correctly using the above formula, the sliding value will be off by a pixel or two which becomes noticeable as we move to a greater number. For example, if we have the slide constant as 50px and we want to display the number 1 we would assume that the slide value should be 100 but for some reason, it might be 101. Similarly, if we want to display the number 2 it can be 152. so if we want to display the number 9 it will be 509, which is off by 9 pixels and very noticeable. The salt is the value that helps balance this anomaly. Even I don't know the exact reason why it happens. It happens for some fonts and font sizes and for some, it does not.</div>
</div>

<p>So now we just have to put all these functions together. Here is what the final js code will look like</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get_number_digits</span>(<span class="hljs-params">number</span>)</span>{
    <span class="hljs-keyword">if</span> (number == <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>

    <span class="hljs-keyword">let</span> number_of_digits = <span class="hljs-number">0</span>
    <span class="hljs-keyword">while</span>(number &gt; <span class="hljs-number">0</span>) {
        number = <span class="hljs-built_in">Math</span>.floor(number/<span class="hljs-number">10</span>)
        number_of_digits ++
    }
    <span class="hljs-keyword">return</span> number_of_digits
}


<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">make_number_containers</span>(<span class="hljs-params">number_of_digits</span>) </span>{
    <span class="hljs-keyword">let</span> counter_c = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'cc'</span>)

    <span class="hljs-comment">// creating a number container for each digit of the number</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> index = number_of_digits; index &gt; <span class="hljs-number">0</span>; index--) {

        <span class="hljs-comment">// creating outer container and adding the required class and id</span>
        <span class="hljs-keyword">let</span> outer_c = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>)
        outer_c.classList.add(<span class="hljs-string">'outer-container'</span>)

        <span class="hljs-comment">// creating number container and adding the required class</span>
        <span class="hljs-keyword">let</span> num_c = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"div"</span>)
        num_c.classList.add(<span class="hljs-string">'number-container'</span>)
        num_c.id = <span class="hljs-string">'nums'</span> + index

        <span class="hljs-comment">// adding number div inside number container. one for each from 0-9</span>
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) {
            <span class="hljs-keyword">let</span> num = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>)
            num.classList.add(<span class="hljs-string">'number'</span>)
            num.innerText = i
            num_c.appendChild(num)
        }

        outer_c.appendChild(num_c)
        counter_c.appendChild(outer_c)
    }

}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">counter_setter</span>(<span class="hljs-params">number,salt</span>) </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> index = <span class="hljs-number">1</span>; index &lt;= number_of_digits; index++) {
        <span class="hljs-comment">// getting the correct number container</span>
        <span class="hljs-keyword">let</span> id = <span class="hljs-string">'nums'</span> + index
        <span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.getElementById(id)

        <span class="hljs-comment">// Geting the last digit of number</span>
        <span class="hljs-keyword">const</span> digit = (number % <span class="hljs-number">10</span>); 
        <span class="hljs-keyword">let</span> value = <span class="hljs-built_in">Math</span>.floor(SLIDE_CONST * digit)
        value = <span class="hljs-built_in">Math</span>.round(value + (salt * digit)) <span class="hljs-comment">// adding salt to the value</span>

        <span class="hljs-comment">// updating the translate value of the div after 200ms</span>
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> { div.style.transform = <span class="hljs-string">`translateY(-<span class="hljs-subst">${value}</span>px)`</span> }, <span class="hljs-number">200</span>)
        number = <span class="hljs-built_in">Math</span>.floor(number / <span class="hljs-number">10</span>); <span class="hljs-comment">// Remove the last digit</span>
    }
}

<span class="hljs-keyword">const</span> SLIDE_CONST = <span class="hljs-number">70</span>
<span class="hljs-keyword">let</span> number_counter = <span class="hljs-number">1238</span>
<span class="hljs-keyword">let</span> salt = <span class="hljs-number">0</span>
<span class="hljs-keyword">let</span> number_of_digits = get_number_digits(number_counter)
<span class="hljs-keyword">let</span> btn_c = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'bc'</span>)


make_number_containers(number_of_digits)
counter_setter(number_counter, salt)

btn_c.addEventListener(<span class="hljs-string">'click'</span>,<span class="hljs-function">(<span class="hljs-params">event</span>)=&gt;</span>{
    <span class="hljs-keyword">if</span> (event.target.tagName == <span class="hljs-string">'INPUT'</span>){
        <span class="hljs-keyword">if</span>(event.target.id == <span class="hljs-string">"f"</span>) number_counter ++
        <span class="hljs-keyword">if</span>(event.target.id == <span class="hljs-string">"b"</span>) number_counter --
        <span class="hljs-built_in">console</span>.log(number_counter);
        counter_setter(number_counter, salt)
    }
})
</code></pre>
<ol>
<li><p><code>get_number_digits(number)</code>: This function calculates the number of digits in a given number. It returns 1 if the number is 0 and counts the digits using a <code>while</code> loop for positive numbers.</p>
</li>
<li><p><code>make_number_containers(number_of_digits)</code>: This function creates a set of HTML containers for displaying individual digits of a number. It appends these containers to an element with the id 'cc'.</p>
</li>
<li><p><code>counter_setter(number, salt)</code>: This function updates the display of the individual digit containers to simulate a sliding effect. It takes the <code>number</code> and <code>salt</code> as parameters and adjusts the position of each digit container based on these values.</p>
</li>
<li><p>Constants and variables: They define a constant <code>SLIDE_CONST</code> with a value of 70 and initializes variables <code>number_counter</code>, <code>salt</code>, and <code>number_of_digits</code>. The <code>number_counter</code> represents the current number, while <code>salt</code> is used for adjusting the sliding effect. The <code>number_of_digits</code> is calculated using the <code>get_number_digits</code> function.</p>
</li>
<li><p><code>btn_c</code> is assigned a reference to an HTML element with the id 'bc', which is expected to be a button.</p>
</li>
<li><p>The code calls <code>make_number_containers(number_of_digits)</code> to create the initial digit containers based on the number of digits in <code>number_counter</code>.</p>
</li>
<li><p>It calls <code>counter_setter(number_counter, salt)</code> to set the initial display of the digit containers based on the <code>number_counter</code> and <code>salt</code>.</p>
</li>
<li><p>An event listener is added to <code>btn_c</code> to listen for click events on its child elements. When a click occurs on an input element inside <code>btn_c</code>, it checks the element's <code>id</code> attribute. If it's "f," it increments <code>number_counter</code>; if it's "b," it decrements <code>number_counter</code> and then logs the updated value to the console. Finally, it calls <code>counter_setter</code> to update the display based on the new <code>number_counter</code> value.</p>
</li>
</ol>
<p>Overall, this code creates a visual representation of a number with sliding digits and allows the user to increment or decrement the displayed number using buttons. The sliding effect is controlled by the <code>counter_setter</code> function and the number of digits in the displayed number is dynamically determined by <code>get_number_digits</code>.</p>
<p>Here's how it looks in action under the hood</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694599370436/037ab062-c144-407c-b719-ae9992cd32c1.gif" alt class="image--center mx-auto" /></p>
<p>Access the code from <a target="_blank" href="https://github.com/cybertron15/Blog-content/tree/main">GitHub repository</a></p>
<p>If you have reached till here thanks for reading and I hope it helped you in some way. This was my first blog and I hope you guys like it. If you have any suggestions/tips/corrections please feel free to write it down in the comments section.</p>
<p>Happy coding!!!</p>
]]></content:encoded></item></channel></rss>