<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chamara Senarath on Medium]]></title>
        <description><![CDATA[Stories by Chamara Senarath on Medium]]></description>
        <link>https://medium.com/@chamaraS?source=rss-c637e72c5493------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lz_6P98wFaRa2d8izPIkQA.jpeg</url>
            <title>Stories by Chamara Senarath on Medium</title>
            <link>https://medium.com/@chamaraS?source=rss-c637e72c5493------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 20:29:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chamaraS/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Simple Git GUI for VS Code That Just Works]]></title>
            <link>https://medium.com/@chamaraS/the-simple-git-gui-for-vs-code-that-just-works-5d63fa7bd04e?source=rss-c637e72c5493------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d63fa7bd04e</guid>
            <dc:creator><![CDATA[Chamara Senarath]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 14:56:02 GMT</pubDate>
            <atom:updated>2025-07-30T14:56:02.952Z</atom:updated>
            <content:encoded><![CDATA[<h4>Finally, a Git interface that feels as natural as writing code. Here’s how GitDash brings visual version control directly into your editor without the bloat.</h4><h3>The Problem With Git Tools Today</h3><p>Every developer has been there. You’re coding in VS Code, completely in the zone, when you need to check your Git history. Your options are:</p><ul><li><strong>Terminal commands</strong>: Cryptic output that hurts your eyes</li><li><strong>Separate Git clients</strong>: Heavy applications that take forever to load</li><li><strong>Bloated extensions</strong>: Feature-packed tools that overwhelm your workspace</li></ul><p>What if there was a <strong>fourth option</strong>? A Git GUI that’s lightweight, intuitive, and lives seamlessly inside VS Code?</p><p>That’s exactly why I built <strong>GitDash</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ckjiJRW92HRITb3tA7P1pg.png" /></figure><h3>Simple by Design, Powerful by Nature</h3><p>GitDash follows one core principle: <strong>Git operations should feel effortless</strong>.</p><p>Instead of cramming every possible Git feature into a complex interface, GitDash focuses on what developers actually need daily:</p><h3>Visual Commit History</h3><p>See your project’s timeline clearly with:</p><ul><li>Clean, readable commit information (hash, author, message, date)</li><li>Visual branch indicators that actually make sense</li><li>Smooth navigation through your repository’s story</li></ul><h3>Smart Search &amp; Filtering</h3><p>Find what you need instantly:</p><ul><li><strong>Author filtering</strong>: Type a name, see their commits</li><li><strong>Message search</strong>: Search commit messages as you type</li><li><strong>Date range filtering</strong>: Focus on specific time periods</li><li><strong>Branch views</strong>: See commits from particular branches</li></ul><p>No complex queries. No memorizing syntax. Just type and find.</p><h3>Intuitive Branch Management</h3><p>Working with branches becomes natural:</p><ul><li>See all your branches at a glance</li><li>Create new branches from any commit with one click</li><li>Switch between branches safely with clear confirmations</li><li>Understand remote relationships without confusion</li></ul><h3>The Beauty of Lightweight Design</h3><h3>Built for VS Code, Not Against It</h3><p>GitDash doesn’t fight your editor — it enhances it:</p><ul><li><strong>Status bar integration</strong>: One click access without disrupting your workflow</li><li><strong>Memory efficient</strong>: Doesn’t slow down your editor like heavy extensions</li><li><strong>Clean interface</strong>: Only shows what you need, when you need it</li></ul><h3>Operations That Feel Natural</h3><p>The Git operations that used to stress you out now feel like second nature:</p><ul><li><strong>Safe checkout</strong>: Switch to any commit with helpful warnings</li><li><strong>One-click cherry-pick</strong>: Apply changes from specific commits easily</li><li><strong>Smart revert</strong>: Undo changes without fear</li><li><strong>Quick fetch</strong>: Update remote information seamlessly</li></ul><p>Every operation includes <strong>smart confirmations</strong> — no more accidental disasters.</p><h3>Why Simple Wins</h3><h3>Less Cognitive Load</h3><p>When your Git tool is intuitive, you spend less mental energy on version control and more on actual coding. GitDash’s clean interface means:</p><ul><li>No hunting through nested menus</li><li>No remembering complex keyboard shortcuts</li><li>No deciphering confusing icons</li><li>No overwhelming feature lists</li></ul><h3>Faster Adoption</h3><p>Your team doesn’t need training sessions or documentation marathons. GitDash is so intuitive that developers start using it productively within minutes.</p><h3>Better Daily Workflow</h3><p>Simple tools get used more often. When Git operations are pleasant:</p><ul><li>You commit more frequently</li><li>You create feature branches naturally</li><li>You explore code history confidently</li><li>You collaborate more effectively</li></ul><h3>Real-World Simplicity</h3><h3>Getting Started (2 Minutes)</h3><ol><li><strong>Install</strong>: Search “GitDash” in VS Code Extensions</li><li><strong>Open</strong>: Click the GitDash button in your status bar</li><li><strong>Explore</strong>: Your Git history is now visual and navigable</li></ol><p>That’s it. No configuration files, no setup wizards, no complicated preferences.</p><h3>Daily Usage (Effortless)</h3><ul><li><strong>Check history</strong>: One click on the status bar</li><li><strong>Find commits</strong>: Start typing in the search box</li><li><strong>Create branches</strong>: Click any commit</li><li><strong>Switch branches</strong>: Click and confirm</li></ul><h3>Advanced Features (When You Need Them)</h3><p>GitDash grows with you. Advanced features are available but never in your way:</p><ul><li><strong>Cherry-picking</strong>: For selective change application</li><li><strong>File inspection</strong>: See what changed in each commit</li><li><strong>Remote management</strong>: Handle remote branches cleanly</li></ul><h3>The Power of Focus</h3><h3>What GitDash Does Best</h3><p>Instead of trying to be everything to everyone, GitDash excels at core Git workflows:</p><ul><li><strong>Visual history exploration</strong></li><li><strong>Quick commit searching</strong></li><li><strong>Safe branch operations</strong></li><li><strong>Intuitive navigation</strong></li><li><strong>Clean, distraction-free interface</strong></li></ul><h3>What GitDash Doesn’t Try to Be</h3><ul><li>A complex merge tool (VS Code handles that beautifully)</li><li>A project management system (stay focused on code)</li><li>A feature-heavy Swiss Army knife (simplicity wins)</li></ul><p>This focus means GitDash does what it does <strong>really well</strong> without bloating your editor.</p><h3>The GitDash Philosophy: Less is More</h3><p>In a world of feature-bloated developer tools, GitDash takes a different approach:</p><ul><li>Simple interfaces reduce errors</li><li>Clear workflows improve productivity</li><li>Lightweight tools don’t slow you down</li><li>Focus enables mastery</li></ul><h3>Ready to Simplify Your Git Workflow?</h3><p>GitDash is free, lightweight, and available now in the VS Code marketplace. No credit cards, no sign-ups, no complicated installations.</p><p>Try it on your current project. See how natural Git operations can feel when the tool gets out of your way and lets you focus on what matters: your code.</p><p>If GitDash simplifies your development workflow (and I’m confident it will), consider leaving a ⭐ review to help other developers discover it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l2h2ob1Yp0IQ22YTaHIVJQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d63fa7bd04e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning Zed into My Productivity Beast ]]></title>
            <link>https://medium.com/@chamaraS/turning-zed-into-my-productivity-beast-ffe5be1900a3?source=rss-c637e72c5493------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffe5be1900a3</guid>
            <category><![CDATA[zed]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[code-editor]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[vscod]]></category>
            <dc:creator><![CDATA[Chamara Senarath]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 14:05:04 GMT</pubDate>
            <atom:updated>2025-01-26T14:05:04.216Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnGHCJBUjJdvtTW_h3vuRQ.png" /></figure><h4>A Farewell to VS Code</h4><p>Hey, coders! 👨‍💻</p><p>For the longest time, Visual Studio Code was my go-to code editor. It was a one-stop shop where I could handle almost everything, whether it was version control with Git or API testing, without switching between applications. Extensions like <a href="https://marketplace.visualstudio.com/items?itemName=mhutchie.git-graph">Git Graph</a> and <a href="https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens">GitLens</a> made managing Git a breeze, and the <a href="https://marketplace.visualstudio.com/items?itemName=Postman.postman-for-vscode">Postman</a> extension helped streamline API testing.</p><p>That said, I was mindful of not overloading VS Code with extensions, as it could slow down performance. I relied heavily on custom keyboard shortcuts for tasks like Git checkout, pull, and stash, all achievable with a single click.</p><p>Making VS Code a productivity powerhouse is a topic for another day, though. Today, let me share how I turned Zed into my new productivity beast.</p><p><strong>Why Consider Zed?</strong></p><p>I first heard about Zed around mid-2024. Curious, I installed it to test things out. It blew me away with its speed and lightweight design. While many users have shown side-by-side comparisons proving Zed’s speed, I wasn’t initially sold. I thought, <em>“Saving a few milliseconds here and there won’t really make a difference.”</em></p><p>But after a few hours of using Zed, I could feel the difference, especially on long coding sessions. Its responsiveness made coding feel smoother.</p><p><strong>Did I Switch to Zed Immediately?</strong></p><p>Nope! Despite its speed, I initially stuck with VS Code. Why? Because Zed lacked some key features:</p><ul><li>No intuitive Git panel like VS Code’s.</li><li>Language servers weren’t as polished.</li><li>The ecosystem lacked extensions.</li></ul><p>While there’s a CLI tool called <a href="https://github.com/jesseduffield/lazygit">Lazygit</a> for Git, I found it cumbersome at first. So, I set Zed aside but kept an eye on its updates, hoping it would evolve into something I could use.</p><p><strong>The Turning Point: Learning Vim</strong></p><p>Back in university, I learned Vim as part of a course, but I wasn’t impressed. A friend tried convincing me by showing off Vim’s “magic,” but my thoughts were: <em>“Why should I memorize all these commands just to code?”</em></p><p>Fast forward to late 2024, my YouTube recommendations kept bombarding me with Vim tutorials. After weeks of ignoring them, I decided to give Vim another shot, but only for personal projects so it wouldn’t impact my work productivity.</p><p>To ease into it, I used the <a href="https://marketplace.visualstudio.com/items?itemName=vscodevim.vim">Vim</a> plugin in VS Code. Within two weeks, I got comfortable with basic motions and commands (e.g., y, yiw for copying or v, viw for selecting). By the end of a month, I was hooked. Navigating without a mouse felt more ergonomic and efficient.</p><p>However, using Vim inside VS Code wasn’t perfect. Over time, I noticed performance issues on larger projects, which reignited my interest in Zed.</p><p><strong>Making the Switch to Zed</strong></p><p>Zed natively supports Vim, so transitioning was seamless. This time, in January 2025, most of my initial concerns with Zed were resolved:</p><ul><li>It was still blazing fast.</li><li>My newfound Vim knowledge made using tools like Lazygit a breeze.</li></ul><p>To address the lack of Git panel, I revisited <a href="https://github.com/jesseduffield/lazygit">Lazygit</a>. It felt intuitive now that I was fluent with Vim motions. I also paired Lazygit with <a href="https://github.com/dandavison/delta">Delta</a>, a syntax-highlighting pager for Git diffs, to improve my workflow.</p><p>Here’s how I integrated Lazygit into Zed:</p><p><strong>Creating a Task for Lazygit</strong></p><pre>{<br>  &quot;label&quot;: &quot;start lazygit&quot;,<br>  &quot;command&quot;: &quot;lazygit&quot;,<br>  &quot;use_new_terminal&quot;: true,<br>  &quot;reveal_target&quot;: &quot;center&quot;<br>}</pre><p><strong>Assigning a Shortcut</strong></p><pre>{<br>  &quot;context&quot;: &quot;Workspace&quot;,<br>  &quot;bindings&quot;: {<br>    &quot;cmd-g&quot;: [&quot;task::Spawn&quot;, { &quot;task_name&quot;: &quot;start lazygit&quot; }]<br>  }<br>}</pre><p>Now, pressing cmd+g opens Lazygit in Zed’s center terminal.</p><p><strong>Additional Shortcuts</strong></p><p>I wanted direct shortcuts for pulling and switching branches, so I added these:</p><pre>{<br>  &quot;context&quot;: &quot;Workspace&quot;,<br>  &quot;bindings&quot;: {<br>    &quot;cmd-0&quot;: &quot;branches::OpenRecent&quot;,<br>    &quot;cmd-9&quot;: [&quot;task::Spawn&quot;, { &quot;task_name&quot;: &quot;git pull&quot; }]<br>  }<br>}</pre><p><strong>Note:</strong> The cmd-0 shortcut doesn’t exactly allow you to check out any branch. It only displays recently used branches. For me, this usually gets the job done. On the rare occasion it doesn’t, I rely on Lazygit for branch management.</p><p>For Git pull, you’ll need another task:</p><pre>{<br>  &quot;label&quot;: &quot;git pull&quot;,<br>  &quot;command&quot;: &quot;git pull&quot;,<br>  &quot;hide&quot;: &quot;always&quot;<br>}</pre><p><strong>Boosting Productivity with Shortcuts</strong></p><p>Here are a few other shortcuts I use:</p><ul><li>cmd+l : Toggle code folding.</li><li>cmd+[ : Jump to the previous cursor point.</li><li>cmd+] : Jump forward.</li><li>jk keys : Map to Vim’s Esc key.</li><li>Project panel shortcuts for file creation, renaming, and deletion.</li></ul><p>I really wanted to create all these shortcuts as Cmd+Shift+Key, but Zed does not support it at the time of writing.</p><p>You can find my complete keymap configuration <a href="https://gist.github.com/chamara-senarath/d2a2a96c4f1a619044255c09cefc9662">here</a>.</p><p><strong>Customizing Zed’s Appearance</strong></p><p>I prefer a clean, minimal workspace. My setup includes:</p><ul><li>Theme: GitHub Dark.</li><li>Font: JetBrains Mono.</li><li>Tabs hidden for a clutter-free look.</li><li>Custom red outline on the active file when the project panel is focused.</li></ul><p>Find my full zed settings <a href="https://gist.github.com/chamara-senarath/df0dd7a42c64315cb53474a947c85c1b">here</a>.</p><p><strong>Should You Switch?</strong></p><p>Even though I’m really enjoying Zed at the moment, it is still in the development stage. I am mainly working on TypeScript and React, and one of the main issues I have at the time of writing is that it doesn’t fully support Emmet inside .tsx files. For example, if I open an HTML tag, it doesn’t automatically create the closing tag. Additionally, sorting doesn’t work well for nested objects in JavaScript.</p><p>Despite these issues, I am happy with everything else Zed offers. For me, it’s an editor I can stick with long-term. However, based on your requirements and the tech stack you use, Zed might feel different for you.</p><p>The best way to decide is to try Zed for a few days — ideally with your personal projects — so you can test it out without impacting your professional productivity.</p><p>If you found this article helpful, don’t forget to clap and share it! For more content like this, follow me on <a href="https://www.linkedin.com/in/chamarasenarath/">LinkedIn</a>. Let’s connect and talk productivity, coding, and more! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffe5be1900a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Fixed Sluggish Performance in My React App with Virtual Rendering Magic]]></title>
            <link>https://medium.com/@chamaraS/how-i-fixed-sluggish-performance-in-my-react-app-with-virtual-rendering-magic-a964af51feae?source=rss-c637e72c5493------2</link>
            <guid isPermaLink="false">https://medium.com/p/a964af51feae</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[virtual-renderings]]></category>
            <dc:creator><![CDATA[Chamara Senarath]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 12:37:56 GMT</pubDate>
            <atom:updated>2025-01-11T12:37:56.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7dsxUpIZKAdebFlaFOR_g.png" /></figure><p>Hey Coders!</p><p>Hey there, fellow devs! Have you ever stared at a gigantic list in your React app and thought, “There’s got to be a better way to handle this”? Well, today’s your lucky day! Let’s talk about how to make rendering massive data sets as smooth as butter in React. Picture this: you’re working on a feature with a massive scrollable list of dropdowns, and each dropdown opens up to reveal even more data. It’s like opening a Matryoshka doll but with code. Now imagine your users’ frustration as the page becomes slower than your grandma’s dial-up internet.</p><p>Been there? Me too. This is exactly the problem I faced. But fear not! I found a solution that’s as smooth as butter — Virtualizing a list! Let’s break it down.</p><h3>Why use virtualized rendering?</h3><p>Here’s a common scenario: React developers often use the map function to render lists with multiple rows. While it’s straightforward, it turns into a nightmare when you’re dealing with thousands of rows. Why? Because the browser insists on creating thousands of DOM elements, even though most of them are hidden behind the scrollbar.</p><p>Rendering a DOM element is no joke. It eats up physical memory and taxes the CPU and GPU, especially when the DOM needs to adjust for user interactions like scrolling.</p><p>So, what happens when you try to render massive lists in one go?</p><ul><li><strong>High memory usage</strong>: Your browser feels like it’s running a marathon.</li><li><strong>Increased CPU/GPU load</strong>: Scrolling becomes jerky and unresponsive.</li><li><strong>Low frame rate</strong>: Your app starts resembling a slideshow instead of a smooth, interactive experience.</li></ul><p>And we all know, no one likes a sluggish app.</p><h3>Enter Virtualized Rendering: The Hero We Needed</h3><p>The idea behind virtualized rendering is beautifully simple. :</p><blockquote><em>“Render only what’s visible.”</em></blockquote><p>Instead of stuffing the DOM with thousands of elements, why not load only what’s in view and dynamically replace those elements as the user scrolls? It’s efficient, it’s sleek, and it’s downright brilliant.</p><p>Let’s look at a visual explanation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qg9WnooWrwcxnu88gaHjTg.png" /><figcaption><em>Difference in scrolling between a regular and virtualized list</em></figcaption></figure><p>Here’s the gist:</p><ol><li>Only elements in a specific viewport (or pane) are added to the DOM.</li><li>As the user scrolls, out-of-view elements are replaced with new ones.</li></ol><h3>Steps to Implement Virtualized Lists</h3><p>To implement this, we need to account for:</p><h3>1. Setting Up the Viewport</h3><p>The viewport is the visible portion of the list. Think of it as the “window” users see. Start by determining the height of this viewport. It’s crucial because only the items within this height will be rendered.</p><h3>2. Calculating the Number of Items in View</h3><p>This depends on whether your items have:</p><p><strong>Fixed Heights</strong>:</p><p>Divide the viewport height by the height of a single item. For example, if your viewport is 500px tall and each item is 50px, you can fit 10 items.</p><p><strong>Dynamic Heights</strong>:</p><p>This is trickier. You’ll need to measure each item’s height dynamically as it loads. Libraries like react-window have built-in methods for handling this.</p><h3>3. Updating Items on Scroll</h3><p>Keep track of the scroll position. As the user scrolls, calculate which items should now be visible and update the rendered list accordingly. This ensures a smooth experience and keeps the DOM light.</p><h3>Why I Chose react-window</h3><p>After exploring several libraries, react-window stood out. Here’s why:</p><ul><li><strong>Simplicity</strong>: It’s lightweight and focuses on doing one thing really well.</li><li><strong>Customizability</strong>: You can easily create lists, grids, or any other virtualized components.</li><li><strong>Performance</strong>: It’s optimized for speed and low memory usage, even with huge datasets.</li></ul><h3>Implementation Code Snippet</h3><p>Here’s a quick example of using react-window to render a list:</p><pre>import React from &#39;react&#39;;<br>import { FixedSizeList as List } from &#39;react-window&#39;;<br><br>const MyVirtualizedList = ({ items }) =&gt; {<br>  const Row = ({ index, style }) =&gt; (<br>    &lt;div style={style}&gt;<br>      {items[index]}<br>    &lt;/div&gt;<br>  );<br>  return (<br>    &lt;List<br>      height={600}<br>      itemCount={items.length}<br>      itemSize={50}<br>      width={800}<br>    &gt;<br>      {Row}<br>    &lt;/List&gt;<br>  );<br>};<br>export default MyVirtualizedList;</pre><p>In this snippet:</p><ul><li>height and width define the viewport dimensions.</li><li>itemCount is the total number of items.</li><li>itemSize is the height of each item (for fixed-height items).</li><li>Row handles rendering each visible item.</li></ul><h3>Final Thoughts</h3><p>Virtualizing your lists is a game-changer. It’s like swapping out your old, clunky CRT monitor for a sleek, ultra-thin LED display. Your users will thank you, your app’s performance will soar, and you’ll feel like a coding wizard.</p><p>So next time your app struggles with rendering massive data sets, remember: Virtualization to the rescue!</p><p>Happy coding, folks! And may your scrollbars always be smooth. 😎</p><p>Follow me on <a href="https://www.linkedin.com/in/chamarasenarath">LinkedIn</a> for more tips and tricks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a964af51feae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Microservice Architecture with Node.js: Part 2]]></title>
            <link>https://medium.com/@chamaraS/building-a-microservice-architecture-with-node-js-part-2-e7f4a28918b6?source=rss-c637e72c5493------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7f4a28918b6</guid>
            <dc:creator><![CDATA[Chamara Senarath]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 12:41:34 GMT</pubDate>
            <atom:updated>2024-03-22T12:42:59.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GETDPAKhWPifhCcYOuInQ.png" /></figure><p>Hey there, coders!</p><p>In my previous post about microservices, we dipped our toes into the world of microservices architecture. We covered the basics like what it is, how it differs from the monolithic approach, and what a service registry is all about.</p><p>This time, we’re diving in and building a service registry from scratch in Node.js! We’ll also use this registry to manage a couple of independent services, showcasing a true microservices architecture in action. Buckle up!</p><h4><strong>The Architecture</strong></h4><p>The architecture is pretty straightforward. We’ll have a Node.js server acting as our service registry, listening on port 3000. Then, we’ll need three more Node.js instances — these will be our services. The beauty of microservices is that these services can be written in any language you like, but for consistency, we’ll stick with Node.js in this example.</p><p>The first two services will provide the same functionality (called “service 1”) but with different versions. The third service will offer a different functionality altogether (called “service 2”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ZmD-KWrVdA05rVumquxyEw.png" /></figure><h4>Setting Up the Service Registry</h4><p>We’ll use Express.js to create a simple HTTP server for our service registry. If you don’t have Node.js and npm set up, get those installed first. Then, you can install Express using:</p><pre>npm install express --save</pre><p>Create an index.js file in your root directory. This will be the entry point for our server. We&#39;ll need to make some adjustments to package.json as well. Since we&#39;re using import statements instead of require, add &quot;type&quot;: &quot;module&quot; to your package.json file. Then, under the &quot;scripts&quot; section, add &quot;start&quot;: &quot;node index.js&quot; for easy server startup.</p><p>Now, in index.js, let&#39;s import Express and create a server instance. We&#39;ll also define a simple GET endpoint (you can return anything from this one).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTSqA90H-9MEr0Xxsggjvw.png" /></figure><h4><strong>Registering Services</strong></h4><p>Create serviceRegistry.js in your root directory and add the following code. Here, we&#39;ll create a function to register services. We&#39;ll use an object to store service information, with keys constructed by concatenating the service name, version, IP, and port. This ensures each service has a unique key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnh-LRlStTZdxHahYaiGKQ.png" /></figure><p>The registerService function checks if the key already exists. If not, it creates a new service object with details like timestamp, IP, port, name, and version. We can add more key-value pairs to this object as needed. Finally, it logs a message confirming service registration.</p><p>If the key already exists, the function only updates the timestamp and logs a message indicating the service has been updated.</p><h4><strong>Putting it All Together</strong></h4><p>Now that we have a registration function, let’s use it in index.js. We&#39;ll create a PUT endpoint that triggers the register function from serviceRegistry.js. We&#39;ll import createServiceRegistry from serviceRegistry.js and call it, passing our logger (console in this case).</p><p>We’ll then define a new PUT endpoint that expects serviceName, serviceVersion, and servicePort as request parameters. Inside the function, we&#39;ll extract these parameters and handle IPv6 addresses appropriately before registering the service using our serviceRegistry. Upon successful registration, the function returns the unique service key as the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMYxj_IDlfph92OYxJkYkA.png" /></figure><h4><strong>Testing Our Registry</strong></h4><p>Fire up Postman or Insomnia and send a PUT request following this pattern to register service1 version 1.0.0 that runs on port 3001:</p><pre>http://localhost:3000/register/service1/1.0.0/3001</pre><p>You should see a message confirming service registration.</p><h4><strong>Finding Services</strong></h4><p>Now, let’s implement a way to find registered services. In serviceRegistry.js, create a getCandidate function that accepts a service name and version. Since microservices can have multiple instances providing the same service, this function will return any available candidate.</p><p>We’ll use the semver package to compare versions easily. You can install it using:</p><pre>npm install semver</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACEo8zYr_1mbwxvYgU8VqA.png" /></figure><p>After finding candidates, we’ll need to select one candidate. For simplicity, we’ll use a random selection method in this example. You can use an algorithm like round-robin.</p><p>Now, let’s create a route for this function in index.js. We&#39;ll extract serviceName and serviceVersion from request parameters and use getCandidate to get a candidate. If no candidate is found, we&#39;ll return a 404 error message. Otherwise, we&#39;ll return the found candidate details as the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8c6eSzkoqwvXYW0Sfy1UQ.png" /></figure><p>Test this out using Postman/Insomnia with a GET request to:</p><pre>http://localhost:3000/find/service1/1.0.0</pre><h4><strong>Unregistering Services</strong></h4><p>Microservices are dynamic, and sometimes services need to be shut down or removed from the registry. To handle this, we’ll create a function to unregister services.</p><p>In serviceRegistry.js, add a function to remove a service by its key. This function simply deletes the corresponding entry from the service registry object and logs a message confirming the deregistration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*859NFIBuC96vB4Xh80i_oQ.png" /></figure><p>We’ll then update index.js to create a DELETE route handler for this function. Similar to registration, this function calls the unregister method from serviceRegistry.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j87mCrn4u4O_w7sZY4Ilng.png" /></figure><h4><strong>Building the Services</strong></h4><p>Now, let’s create the actual services that will register themselves with our service registry. We’ll use separate files for each service and version (e.g., service_1_v_1.0.0.js). We&#39;ll also create a helper file (serviceHandler.js) to handle registration and deregistration logic.</p><p>In a real-world scenario, these services could reside on different servers and be written in various languages. Here, we’ll keep them in the same project for simplicity.</p><p><strong>serviceHandler.js<br></strong>This file will contain functions for registering and unregistering services. The registerService function calls the registry&#39;s registration endpoint, passing service details like name, version, and port. The unregisterService function calls the registry&#39;s deregistration endpoint when the service shuts down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7J6KYqwegxvr24Rp50h4PQ.png" /></figure><p><strong>service_1_v_1.0.0.js (example service file)<br></strong>This file defines a basic Express app with a simple GET endpoint for demonstration purposes. It also includes registration and deregistration logic using the serviceHandler.js helper.</p><p>The service registers itself with the registry during startup and unregisters upon encountering exceptions or termination signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5TuwiBsQNFzchYFs2iG8A.png" /></figure><h4><strong>Running the Application</strong></h4><ol><li>Start the main server (service registry) using npm start.</li><li>Run each service instance individually using node service_X_v_Y.js commands (replace X and Y with service and version numbers).</li></ol><p>You should see messages in the console reflecting service registration and deregistration as you start and stop the services.</p><p>This article lays the foundation for building a microservices architecture with service discovery using a Node.js registry. We’ve covered registering, finding, and unregistering services.</p><p>In the next part, we’ll explore how to handle service failures using circuit breakers, a technique to prevent cascading failures in a distributed system. We’ll also delve into caching services and creating request queues — all essential components for building robust microservices applications.</p><p>For the full code, check out the <a href="https://github.com/chamara-senarath/node-microservice-tutorial">GitHub</a> repository. If you found this article helpful, consider giving it a clap and sharing it! Feel free to follow me on <a href="https://www.linkedin.com/in/chamarasenarath">LinkedIn</a> for more valuable content like this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7f4a28918b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ResizeObserver for React Developers]]></title>
            <link>https://medium.com/@chamaraS/resizeobserver-for-react-developers-a91df3608944?source=rss-c637e72c5493------2</link>
            <guid isPermaLink="false">https://medium.com/p/a91df3608944</guid>
            <dc:creator><![CDATA[Chamara Senarath]]></dc:creator>
            <pubDate>Sat, 30 Dec 2023 16:40:35 GMT</pubDate>
            <atom:updated>2023-12-30T19:13:59.072Z</atom:updated>
            <content:encoded><![CDATA[<h4>Solving ResizeObserver Errors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJHrv-TWumd0rqLjijFq2g.png" /></figure><p>Recently, while working on a React project, I encountered the “ResizeObserver loop completed with undelivered notifications” error. Our team pinpointed that this error arises when the LastPass extension is activated in the browser. Although these errors won’t show up in the production environment and can be ignored safely, handling them during development becomes quite challenging.</p><p>Therefore, I delved into researching this to find a solution. Unfortunately, as of now, I haven’t come across a definitive solution to address this issue. In this blog post, I’ll share insights about ResizeObserver and discuss how I approached resolving the error.</p><h3>What is ResizeObserver?</h3><p>According to the MDN web docs,</p><blockquote>The ResizeObserver interface reports changes to the dimensions of an <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element">Element</a>&#39;s content or border box, or the bounding box of an <a href="https://developer.mozilla.org/en-US/docs/Web/API/SVGElement">SVGElement</a>.</blockquote><p>In simple terms, The ResizeObserver is like a watchman that keeps an eye on the size changes of HTML elements (like divs, images, etc.) or SVG elements.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FGFE5dagX3tKTqkRZg8%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FGFE5dagX3tKTqkRZg8%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExNWsxcDZ3MjB0amJwNDZweWM0d2UwZ2t3dzkzMjgwZTFkbDJtY21sOCZlcD12MV9naWZzX2dpZklkJmN0PWc%2FGFE5dagX3tKTqkRZg8%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6994fe9d742e9c3680018fb4d389ba0/href">https://medium.com/media/e6994fe9d742e9c3680018fb4d389ba0/href</a></iframe><p>Imagine you have a webpage, and you want to know when the size of a specific element changes, for example, when someone resizes the browser window or changes the content inside the element. You can use ResizeObserver to detect these changes and perform actions accordingly.</p><p>The basic usage of ResizeObserver involves creating an instance of the observer, specifying the target element(s) to observe, and defining a callback function that will be triggered when a size change occurs.</p><p>Here’s a simplified example of how ResizeObserver can be used:</p><pre>// Create a new ResizeObserver<br>const resizeObserver = new ResizeObserver(entries =&gt; {<br>  for (let entry of entries) {<br>    // Perform actions based on size changes<br>    console.log(&#39;Element size changed:&#39;, entry.target);<br>    console.log(&#39;New dimensions:&#39;, entry.contentRect.width, entry.contentRect.height);<br>    // Perform actions like adjusting layout, styling, etc.<br>  }<br>});<br><br>// Select the element to observe<br>const targetElement = document.querySelector(&#39;.resize-element&#39;);<br><br>// Start observing the target element<br>resizeObserver.observe(targetElement);</pre><p>When the size of the observed element changes, the callback function provided to ResizeObserver will be executed, allowing us to handle the changes as needed.</p><h3>Observation Errors</h3><p>Observation errors in ResizeObserver generally refer to potential issues or mistakes that can occur when using this API. These errors can arise due to various reasons, including improper handling, incorrect usage, or unexpected behaviour of the observed elements.</p><p>Let’s say you have a webpage with multiple resizable elements. When you resize one element, it triggers a ‘resize event’. This event prompts the browser to check if other elements’ styles or layouts need to change. If these changes in turn cause more resize events, the browser handles these by ensuring it doesn’t endlessly loop through changes. Instead, it prioritizes changes deeper in the webpage structure to avoid infinite cycles.</p><p>If there’s a situation where an element’s resize affects another, which then triggers a change back to the first element (a loop), the browser safeguards against this by controlling the order of processing. If, due to these controls, some resize events are delayed until the next render, the browser reports this issue as an error with the message “ResizeObserver loop completed with undelivered notifications”, ensuring developers are aware of potential problems.</p><p>You can consider the following methods to minimize observation errors:<br>1. Implement proper error handling</p><p>2. Test your code across various scenarios</p><p>3. Implement techniques like debouncing or throttling to manage the frequency of resize events</p><h3>Problem with third-party extensions</h3><p>When third-party extensions are active in your browser and they modify elements on your webpage, observation errors may occur.</p><p>In our case, the LastPass extension adds its icon to input fields on the web pages, triggering ResizeObserver due to element resizing. If we attempt to load another component before ResizeObserver finishes handling all changes, it leads to an error.</p><p>For instance, this issue might arise in the login form. When trying to input login credentials and proceed to the next page by clicking “login,” an error might occur.</p><p>Another possible scenario is when inputs modified by extensions are within a modal with transitions, and the modals are forcibly closed before the transition completes.</p><p>We managed to resolve the modal-related error by allowing the modals to complete their transitions, providing ResizeObserver sufficient time to finish its actions.</p><p>However, in cases where adding a delay isn’t feasible, we needed an alternative solution. After attempting various workarounds, I found the following solution.</p><p>To address the issue, we’ll keep an eye on input elements altered by third-party extensions. Then, we’ll undo these alterations and disconnect the observer during the component’s unmounting phase. This will prevent ResizeObserver from continuing to monitor the element.</p><pre>import { useRef } from &#39;react&#39;<br><br>export default function Login() {<br>    const inputRef = useRef(null)<br><br>    useEffect(() =&gt; {<br>        let resizeObserverEntries = []<br>    <br>        const observer = new ResizeObserver((entries)=&gt;{<br>            resizeObserverEntries = entries<br>        })<br><br>        if(inputRef.current) observer.observe(inputRef.current)<br><br>        return () =&gt; {<br>            resizeObserverEntries.forEach((entry)=&gt;entry.target.remove())<br>            observer.disconnect()<br>        }<br>    },[])<br><br>  return (<br>    &lt;&gt;<br>        &lt;input name=&quot;username&quot; type=&quot;text&quot; /&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><p>In the code above, We’ve used the <em>useRef</em> hook to create a reference for the input named “<em>username</em>”. Some extensions might wrap the input in another element like <em>div</em> and append their elements to it. You need to make any necessary adjustments in such cases. Also, you can create multiple references according to the number of input elements in your code.</p><p>Within the <em>useEffect</em> hook, We’ve set an empty array as the dependency array to invoke the callback function when the component mounts. Inside this callback function, an array named “<em>resizeObserverEntries</em>” is defined to track entries captured by the ResizeObserver.</p><p>Then, we create an instance of <em>ResizeObserver</em> and assign its entries to the <em>resizeObserverEntries</em> array. This instance of <em>ResizeObserver</em> monitors changes in our input element. We pass the reference of our input element to the ResizeObserver’s <em>observe</em> method. Therefore, the <em>ResizeObserver</em> starts monitoring changes in the input element, triggering the callback function when alterations occur. As a result, the <em>resizeObserverEntries</em> array updates when changes are detected in the input element.</p><p>Upon unmounting the current component, it’s essential to revert the changes and disconnect the observer. To achieve this, we use a return callback within the <em>useEffect</em> hook in React. Inside this callback, we remove all entries in the <em>resizeObserverEntries</em> array. However, if specifically targeting modified elements like the icon inserted by LastPass, you’ll need to identify that specific element in the DOM and handle it accordingly within this context. After handling these elements, disconnecting the observer ensures it stops monitoring the element’s changes.</p><p>And that’s a wrap for this blog! Hope you picked up something new about ResizeObserver and its error handling. Stay tuned for more blogs coming your way!</p><p>Follow me on <a href="https://github.com/chamara-senarath"><strong>Github</strong></a>, <a href="https://twitter.com/Chamz_Jay"><strong>Twitter</strong></a><strong> </strong>and <a href="https://www.linkedin.com/in/chamarasenarath"><strong>LinkedIn </strong></a>for more valuable content. Looking forward to sharing more with you soon! 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a91df3608944" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Microservice Architecture with Node.js: Part 1 — Exploring the Foundations]]></title>
            <link>https://medium.com/@chamaraS/building-a-microservice-architecture-with-node-js-part-1-exploring-the-foundations-f0049efe47b8?source=rss-c637e72c5493------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0049efe47b8</guid>
            <dc:creator><![CDATA[Chamara Senarath]]></dc:creator>
            <pubDate>Mon, 15 May 2023 13:44:08 GMT</pubDate>
            <atom:updated>2023-05-15T13:44:08.225Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Microservice Architecture with Node.js: Part 1 — Exploring the Foundations</h3><figure><img alt="Building a Microservice Architecture with Node.js: Part 1 — Exploring the Foundations" src="https://cdn-images-1.medium.com/max/1024/1*UJYR9x_2saQzdFRb--wNdQ.png" /></figure><p>In this series of articles, I will guide you through the process of creating a microservice architecture application using Node.js. Whether you’re a developer looking to expand your knowledge or someone curious about microservices, this blog is for you.</p><p>In the first part of the series, I will introduce you to the basic concepts of microservice architecture.</p><p>As we progress, We will dive deeper into the implementation details and guide you through the step-by-step process of building a microservice application using Node.js. We’ll cover topics such as service discovery, communication between services, scalability, and more.</p><p>So, if you’re ready to embark on this exciting journey of creating a scalable and modular application, stay tuned for the upcoming blogs in this series. Let’s explore the world of microservices together and bring your ideas to life!</p><h3>Microservices Architecture</h3><p>Microservices architecture has emerged as a popular way of building complex applications that can scale and evolve independently. It involves breaking down an application into small, self-contained services, where each service performs a specific task.</p><figure><img alt="small, self-contained services" src="https://cdn-images-1.medium.com/max/940/1*1n3n3ihw1iAX3H5dXiQEcA.png" /></figure><p>These services can be written in different programming languages such as JavaScript, Java, and C. To communicate with each other, microservices use standard HTTP methods.</p><p>One of the benefits of microservices architecture is that if one service fails, it does not cause the entire application to fail, making the system more resilient.</p><h3>Monolithic Vs Microservices</h3><p>A monolithic application bundles all functionality into a single codebase, while microservices divide the application into modular and independent services. For example, an e-commerce application might have separate microservices for user management, inventory, and order processing. Microservices allow for individual development, deployment, and scaling.</p><p>Let’s consider another example to illustrate the difference between a monolith application and a microservices architecture. Imagine a social media platform with features such as user profiles, news feeds, and messaging.</p><p>In a monolith application, all these features would be tightly coupled together within a single codebase. Any changes or updates to one feature would require redeploying the entire application. This can lead to longer development cycles and an increased risk of introducing bugs or unintended consequences.</p><p>On the other hand, a microservices architecture would separate each feature into its own independent service. The user profiles, news feeds, and messaging functionalities would each have their dedicated microservice. This modular approach allows for individual development, scalability, and fault isolation. For example, if the messaging service experiences a high load, it can be scaled independently without affecting other services.</p><p>Additionally, microservices enable the use of different technologies and programming languages. For instance, the user profiles service might be implemented using Java, while the news feeds service could be written in Python. This flexibility allows development teams to choose the most suitable tools for each microservice, leveraging the strengths of different technologies.</p><h3>Essential Concepts for Building a Microservice Architecture</h3><h4>Service discovery</h4><p>Microservices architecture consists of smaller applications that require constant communication through REST APIs. Service discovery, a fundamental pattern in service architecture, allows applications and microservices to automatically locate and communicate with each other. Microservices register their information with the discovery server, facilitating seamless communication between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*5ZB8uzN4CVLQZ0nH.gif" /></figure><p>Let’s consider an example of an e-commerce platform that utilizes a microservices architecture with service discovery. The platform consists of various microservices such as user management, product catalog, and order processing.</p><p>When a user wants to place an order, the order processing microservice needs to communicate with the user management microservice to verify the user’s credentials and the product catalog microservice to check product availability. In a microservices architecture with service discovery, each microservice registers its location and details with the discovery server.</p><p>So, when the order processing microservice needs to communicate with the user management and product catalog microservices, it can rely on the service discovery mechanism to automatically locate the necessary endpoints. It doesn’t need to have hardcoded URLs or IP addresses for each microservice. Instead, it can query the discovery server to get the appropriate endpoints and establish communication seamlessly.</p><p>This way, the microservices can dynamically discover and communicate with each other, even as the system scales or new microservices are added. The service discovery mechanism simplifies the communication process by eliminating the need for manual configuration and ensuring that the microservices can find and interact with one another effectively.</p><p>There are two important patterns that exist you should know about:</p><ol><li>Server-side discovery</li><li>Client-side discovery</li></ol><p>In this article series, we will specifically concentrate on the implementation of client-side discovery using a <strong>service registry</strong>.</p><h4>What is a service registry?</h4><p>A service registry can be defined as a repository or catalog containing the information and configurations of network service instances. Its primary function is to facilitate communication between applications by serving as a data transportation system.</p><figure><img alt="Service registry" src="https://cdn-images-1.medium.com/max/940/1*6EesfOaWblIif3OA351ipw.png" /></figure><p>Each service registers itself with the service registry, supplying comprehensive information such as its host, port, node name, and other relevant metadata specific to the service.</p><p>If the service registry is not accessible, it can be challenging or even impossible to connect to the microservices. That’s why it’s crucial for the service registry to remain available and regularly updated so that clients can obtain accurate information about network locations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*EECHwwvYma6Xd1hj" /></figure><p>That’s all for this blog! I hope you now have a solid understanding of the basic concepts of microservice architecture. In the upcoming blogs, we will delve into the implementation details and cover some key aspects of building a microservice application using Node.js.</p><p>In the next couple of blogs, we will focus on the following topics:</p><p>1. Implementation of a service registry: We will explore how to create and manage a service registry, which plays a vital role in enabling service discovery within a microservice architecture.</p><p>2. Versioning of services: We will discuss strategies for versioning services in a microservice environment, allowing you to introduce updates and improvements without disrupting existing functionality.</p><p>3. Registering services in the Service Register: We will cover the steps involved in registering new services and updating existing service information in the service registry.</p><p>4. Requesting services from the Service Register in the Main Application: We will explore how the main application can interact with the service registry to dynamically locate and consume the required services.</p><p>5. Handling service failure: We will discuss techniques for handling service failures gracefully, ensuring the overall resilience and availability of the microservice architecture.</p><p>6. Caching services: We will explore the use of caching mechanisms to improve performance and reduce the load on the service registry.</p><p>Stay tuned for my upcoming blogs as I dive deeper into these essential topics. Together, we will unlock the power of microservices and build robust, scalable applications using Node.js!</p><p>Follow me on <a href="https://twitter.com/Chamz_Jay"><strong>Twitter</strong></a><strong> </strong>and <a href="https://www.linkedin.com/in/chamarasenarath"><strong>LinkedIn </strong></a>for more valuable content. Looking forward to sharing more with you soon! 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0049efe47b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s use Vue3 Features in Your Vue2 Project]]></title>
            <link>https://medium.com/ascentic-technology/lets-use-vue3-features-in-your-vue2-project-f81a65ec5267?source=rss-c637e72c5493------2</link>
            <guid isPermaLink="false">https://medium.com/p/f81a65ec5267</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Chamara Senarath]]></dc:creator>
            <pubDate>Mon, 08 Aug 2022 06:38:40 GMT</pubDate>
            <atom:updated>2023-02-07T09:23:57.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0CPeW6Behw1o4bdzT5lOw.jpeg" /></figure><p>I have been working on a Vue 2 project for a long time. When I heard the news “Vue 2.7 Released”, I seriously wanted to upgrade our project considering the features they have backported from Vue 3. The backported features are:</p><ul><li>Composition API</li><li>SFC :&lt;script setup&gt;</li><li>SFC : CSS v-bind</li></ul><p>In this article, I will show you, how to upgrade your existing Vue2 project to Vue 2.7 and I will explain how to use the mentioned backported features in your project explaining a small application.</p><h3>Upgrade Guide.</h3><ol><li>Upgrade local <strong><em>@vue/cli-xxx</em></strong> dependencies.</li></ol><pre>npm update -g @vue/cli<br># OR<br>yarn global upgrade --latest @vue/cli</pre><p>2. Remove node_modules folder and the lockfile (package-lock or yarn.lock) and perform a fresh install.</p><p>3. If you were previously using <strong><em>@vue/composition-api</em> </strong>or<br><strong><em>vue-template-compiler,</em> </strong>uninstall them and update the places where you use imports from <strong><em>@vue/composition-api</em></strong> to<strong> <em>vue</em></strong>.</p><p>4. If you run into unused variable lint errors when using &lt;script setup&gt;, update <strong><em>eslint-plugin-vue</em></strong> to the latest version (9+)</p><p>5. If you are using webpack, make sure to include <strong><em>VueLoaderPlugin</em></strong> in your webpack config file</p><pre>// webpack.config.js<br>const { VueLoaderPlugin } = require(&#39;vue-loader&#39;)<br><br>module.exports = {<br>  module: {<br>    rules: [<br>      // ...rules<br>    ]<br>  },<br>  plugins: [<br>    // make sure to include the plugin!<br>    new VueLoaderPlugin()<br>  ]<br>}</pre><h3>Using backported features</h3><p>Now, you are ready to use amazing backported features from Vue 3. Let’s create a small application using the mentioned features. The application is Free Fuel Pass. Imagine you are given a limited amount of free fuel for a week from the government. There is a pass (QR Code) you have to show to your filling station then you can click the Fill Me Up button in your application and you get 1L per click. You can see the eligible weekly quota and the balance is updated each time you press the button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKZykEzX66m-FuPfiwREiQ.png" /></figure><h3>Step 1 — Setting up the environment</h3><ul><li>Since we are creating a new application, you can use your Vue-CLI to create a new project. Enter the following command and select Vue 2</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RjzvpYl8KFTc_2wnUeZPXA.png" /></figure><ul><li>Upgrade your project to vue 2.7 as mentioned in the upgrade guide.</li></ul><h3>Step 2 — Get your hands dirty with vue</h3><p>I have created this application to give you as many examples of backported features as possible in a single application.</p><h4>Starting with our App.vue file.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhxPshyRcrnqMVPLr_LzLw.png" /></figure><p>Just like any other vue file, we have &lt;template&gt;, &lt;script&gt; and &lt;style&gt; sections here. Let’s have a look at the things we have used here. In the template, we have the application title, quota view, and fill me up button. <strong><em>QuotaView</em></strong> and <strong><em>FillMeUp</em></strong> components are imported from the <strong><em>components</em></strong> folder.</p><p><strong><em>QuotaView</em></strong> expects 2 props, which are eligible quota and used quota. Notice how we access them using <strong><em>&lt;script setup&gt;. </em></strong>we are using Vue3’s reactivity to create these two variables. There are two ways you can define a reactive variable in Vue3 (Composition API). You can use <strong><em>reactive</em></strong> or <strong><em>ref</em></strong> methods. There is a difference in using them and we will keep it to discuss in another article. Here, we have assigned 0 to both <strong><em>eligibleQuota</em></strong> and <strong><em>usedQuota</em></strong> variables.</p><p><strong><em>FillMeUp</em></strong> expects 1 prop, which is <strong><em>disabled</em></strong> and it emits <strong><em>click-fill </em></strong>when you click on the button. To handle the <strong><em>click-fill</em></strong> event, we have created <strong><em>handleOnClickFill</em></strong> function and it expects the payload from the <strong><em>click-fill</em></strong> event. In the function, we simply check if the <strong><em>usedQuota</em></strong> value is greater than or equal to <strong><em>eligibleQuota</em></strong> and set <strong><em>isDisabledFill</em></strong> variable to true, and returns from the function if the condition is true. Otherwise, the amount is added to usedQuota. Since we are using <strong><em>ref, </em></strong>you need to include “.value” to read or write from/to a reactive variable inside the <strong><em>script</em></strong>. But, inside the &lt;template&gt;, you can use reactive variables just like you used to do it in vue2 (just by calling the variable name)</p><p>Now, we need to set a random value to our <strong><em>eligibleQuota’s</em></strong> value. So, the best place to do so is inside <strong><em>onMounted</em></strong> lifecycle hook. We are assigning a value between 5 to 25 to <strong><em>eligibleQuota.</em></strong></p><p>Wait... What about the &lt;style&gt;?? Sorry, I am not going to explain them here as there is no change in using CSS in Vue 2.7 😉. But I will explain CSS V-bind in the next section.</p><h4>Fill Me Up</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WInPu7e9_NUPv3sVFbUHCQ.png" /></figure><p>Here, there is only one element in the template, which is our button. button has “fill-me-button” class and it calls <strong><em>handleOnClickFill</em></strong> function on click. As we discussed earlier, this component expects <strong><em>disabled</em></strong> prop, which is defined inside <strong><em>defineProps</em></strong> method. You can pass multiple objects into the defineProps method if you have multiple props. We have assigned this to <strong><em>props</em></strong> constant in order to access props inside the script. If you are not accessing props inside the script, you can ignore assigning this since you can access props inside the template just by calling the name of the property.</p><p>When you click on the button, it fires <strong><em>handleOnClickFill </em></strong>function. Inside the function, we emit ‘click-fill’ event with a payload, which is <strong><em>{amount:1}</em></strong> object. In order to use this emit, first, we have to register it. That’s where the <strong><em>defineEmits</em></strong> method comes into the picture. Similar to props, you can ignore assigning this to a constant if you only using it inside the template. <strong><em>defineEmits</em></strong> method expects an array of strings. Since we have only one event. let’s register it using its name (‘click-fill’).</p><p>We are using ‘disabled’ prop to generate a string to <strong><em>buttonCursor</em></strong> variable. Since we are generating a text, based on another variable (prop), let’s use the <strong><em>computed</em></strong> function. so, if the disabled prop is true, it returns ‘not-allowed’ and if not, it returns ‘pointer’</p><p>Now, let’s see how we can use CSS v-bind. Inside the &lt;style&gt;, we are using <strong><em>v-bind</em></strong> to change the button’s <strong><em>cursor</em></strong> based on the value of the <strong><em>buttonCursor </em></strong>variable.</p><h4>Quota View</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GjsSGLZKXnKFYAa5CTWnA.png" /></figure><p>This is the simplest component of our project. It expects two props, <strong><em>eligibleQuota,</em></strong> and <strong><em>usedQuota. </em></strong>There is a computed function to calculate the balance quota based on the props and the result is assigned to the <strong><em>balanceQuota</em></strong> variable. In the template, it shows the eligible weekly quota and the balance weekly quota.</p><p>So, we have covered how to use reactive variables, define props, define emits, computed properties, lifecycle hooks, and CSS v-bind. but there is one missing part. Now, we know how to replace “this.$emit” with <strong><em>defineEmit</em></strong>. But do you know how to replace “this.$router”? or other properties you used to access with “this” such as prototypes? This is something I struggled to find when working on my project. The best way I found was, to extract these from your current instance’s proxy. Just like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6yht8q1_xkiI8coJDldJ-w.png" /></figure><p>Here I have extracted <strong><em>route</em></strong>, <strong><em>router</em></strong>, and <strong><em>http.</em></strong> Now, you can easily use these in your script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*AbKTVk7l0ivYuA9hWMuCTg.gif" /></figure><p>I believe you have learned how to upgrade your project to Vue 2.7 and how to use the features in your project. You can find the application code on my Github account: <a href="https://github.com/chamara-senarath/free-fuel-pass-example">https://github.com/chamara-senarath/free-fuel-pass-example</a>. Follow me for more articles. ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f81a65ec5267" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ascentic-technology/lets-use-vue3-features-in-your-vue2-project-f81a65ec5267">Let’s use Vue3 Features in Your Vue2 Project</a> was originally published in <a href="https://medium.com/ascentic-technology">Ascentic Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sticky ScrollSpy Table of Contents in Vue.js]]></title>
            <link>https://medium.com/ascentic-technology/sticky-scrollspy-table-of-contents-in-vue-js-73d2d6f0a1cd?source=rss-c637e72c5493------2</link>
            <guid isPermaLink="false">https://medium.com/p/73d2d6f0a1cd</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[scrollspy]]></category>
            <category><![CDATA[table-of-contents]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[sticky]]></category>
            <dc:creator><![CDATA[Chamara Senarath]]></dc:creator>
            <pubDate>Sat, 05 Feb 2022 16:42:07 GMT</pubDate>
            <atom:updated>2022-02-08T04:30:01.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwd5t4k4KiiJVsVTbhrUGA.png" /></figure><h4>Let’s create a</h4><p>A while ago, I was working on a documentation page, I wanted to create a Sticky Table of Contents section with the Scrolling Active States. I searched for some implementation examples on Vue, but couldn’t find what I needed. So here’s a little guide that I hope it’s useful for you to implement on your Vue apps.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F4767352&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fdespicable-me-minions-lets-get-started-happy-excited-gif-4767352&amp;image=https%3A%2F%2Fmedia.tenor.com%2Fr3XdvPsAV3kAAAAN%2Fdespicable-me-minions.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f152eb61b96552df2d9bb54017cba731/href">https://medium.com/media/f152eb61b96552df2d9bb54017cba731/href</a></iframe><h3>Creating our Vue App</h3><p>There are several ways to install Vue, however, installing Vue CLI is the simplest. You can install Vue CLI globally by running the command below:</p><pre>npm install -g @vue/cli</pre><p>Once installation is complete, you can create a new project with the following command:</p><pre>vue create sticky-scrollspy-toc</pre><p>Let’s replace App.vue file with the following code segments.</p><h4>1. The Markup</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSakfv6D0x4BXAjpd1P9MQ.png" /><figcaption>HTML</figcaption></figure><p>In the code above, we have created two sections. The first &lt;<strong><em>div&gt;</em></strong> is for the page content and the second <strong><em>&lt;section&gt;</em></strong> inside the <strong>&lt;<em>nav&gt;</em></strong> is for the table of contents. It is required to have <strong><em>id</em></strong> attributes for each section so that, we can use them to scroll into the corresponding section. <strong><em>href</em></strong> attribute in each list item is used to navigate to section ids.</p><h4>2. Sprinkle some CSS on top</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1-HEGP5YAydSVTN6MfF6w.png" /><figcaption>CSS</figcaption></figure><p>The code above,position: sticky; is used to make the navigation stay in place as you scroll. It is important to add align-self: start; to<em> &lt;nav&gt;.</em> If we would omit it, the &lt;<em>nav&gt;</em> element would be as high as the enclosing &lt;<em>main&gt;</em> element.</p><h4>3. ScrollSpy with IntersectionObserver</h4><p>According to the MDN docs:</p><blockquote><em>“The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport.”</em></blockquote><p>Let’s use the IntersectionObserver in our app, in order to highlight the links in the table of contents based on the page position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnexQ0U-WuKgXU34Uz3PkA.png" /></figure><p>Let’s break down the script:</p><ol><li>We added a reference to the <strong><em>observer</em> </strong>in the component’s data. This is important since we will be using this reference in a few places.</li><li>We initialized the observer in the <strong><em>created</em></strong> hook. Notice that we use <strong><em>this.$el</em></strong> as the observer’s root. You can adjust the threshold to match your page content.</li><li>In mounted hook, we use query selector to catch all the <strong><em>&lt;section&gt;</em></strong> tags that have an id attribute. Using the observer reference, we make each section observed.</li><li>We added the <strong><em>onElementObserved</em></strong> method. In the method, we get all the entries from the observer and we extract <strong><em>target</em></strong> and <strong><em>isIntersecting</em></strong> from each entry. In the for loop, we get the id from the intersecting <strong><em>section </em></strong>and if the section is intersecting, we add <strong><em>active</em></strong> class to the relevant link in the table of contents. Otherwise, we remove <strong><em>active</em></strong> class.</li><li>Finally, we disconnect the observer in <strong><em>beforeDestroy</em></strong> hook to ensure the browser is not computing the intersection after the current page gets destroyed.</li></ol><p>You can see the final result in <a href="https://codesandbox.io/s/sticky-scrollspy-table-of-contents-in-vue-js-xj2mp?file=/src/App.vue"><strong>CodeSandbox</strong></a><strong>. </strong>Feel free to play with it and try it for yourself. 💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73d2d6f0a1cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ascentic-technology/sticky-scrollspy-table-of-contents-in-vue-js-73d2d6f0a1cd">Sticky ScrollSpy Table of Contents in Vue.js</a> was originally published in <a href="https://medium.com/ascentic-technology">Ascentic Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>