<?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 Ramu Narasinga on Medium]]></title>
        <description><![CDATA[Stories by Ramu Narasinga on Medium]]></description>
        <link>https://medium.com/@ramu.narasinga_61050?source=rss-3ddfc36c4e84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GnnjW6aPBDmH1w_WVZGj9w.jpeg</url>
            <title>Stories by Ramu Narasinga on Medium</title>
            <link>https://medium.com/@ramu.narasinga_61050?source=rss-3ddfc36c4e84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 12:31:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramu.narasinga_61050/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[Use degit to download a template in your CLI tool.]]></title>
            <link>https://medium.com/@ramu.narasinga_61050/use-degit-to-download-a-template-in-your-cli-tool-6d2b628ac933?source=rss-3ddfc36c4e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d2b628ac933</guid>
            <category><![CDATA[remotion]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[degit]]></category>
            <category><![CDATA[tarball]]></category>
            <dc:creator><![CDATA[Ramu Narasinga]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 20:14:54 GMT</pubDate>
            <atom:updated>2024-08-16T20:14:54.096Z</atom:updated>
            <content:encoded><![CDATA[<p>I found a file named “degit” in the <a href="https://github.com/remotion-dev/remotion/blob/main/packages/create-video/src/degit.ts">Remotion source code</a>. <a href="https://www.remotion.dev/">Remotion</a> helps you make videos programatically.</p><p>In this article, we will look at the following concepts:</p><ol><li>What is Degit?</li><li>Build a simple degit function inspired by <a href="https://github.com/remotion-dev/remotion/blob/main/packages/create-video/src/degit.ts">Remotion’s degit file</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9HJbUD4G5M4MLeAI3WZ8rA.png" /></figure><h3>What is Degit?</h3><p>I do remember seeing “degit” mentioned in one of the Readmes in the open source, but I could not recall which repository it was so I googled what a degit means and found this <a href="https://github.com/Rich-Harris/degit">degit npm package</a>.</p><p>In simple terms, You can use degit to quickly make a copy of a Github repository by only downloading the latest commit<br>instead of the entire git history.</p><p>Visit the official <a href="https://github.com/Rich-Harris/degit">npm package for degit</a> to read more about this package.</p><p>You can use this degit package to download repos from Gitlab or Bitbucket as well so its not just limited to Github repositories.</p><pre># download from GitLab<br>degit gitlab:user/repo<br># download from BitBucket<br>degit bitbucket:user/repo<br>degit user/repo<br># these commands are equivalent<br>degit github:user/repo</pre><p>Here’s a sample usage in Javascript:</p><pre>const degit = require(&#39;degit&#39;);<br>const emitter = degit(&#39;user/repo&#39;, {<br>    cache: true,<br>    force: true,<br>    verbose: true,<br>});<br>emitter.on(&#39;info&#39;, info =&gt; {<br>    console.log(info.message);<br>});<br>emitter.clone(&#39;path/to/dest&#39;).then(() =&gt; {<br>    console.log(&#39;done&#39;);<br>});</pre><h3>Build a simple degit function inspired by Remotion’s degit file</h3><p>To understand how to build a simple degit function, let’s break down the code from Remotion’s degit.ts file. This file implements a basic version of what the degit npm package does: fetching a GitHub repository’s latest state without downloading the full history.</p><h3>1. Imports used</h3><pre>import https from &#39;https&#39;;<br>import fs from &#39;node:fs&#39;;<br>import {tmpdir} from &#39;node:os&#39;;<br>import path from &#39;node:path&#39;;<br>import tar from &#39;tar&#39;;<br>import {mkdirp} from &#39;./mkdirp&#39;;</pre><ul><li>https: Used to make a network request to fetch the repository.</li><li>fs: Interacts with the file system, such as writing the downloaded files.</li><li>tmpdir: Provides the system’s temporary directory path.</li><li>path: Handles and transforms file paths.</li><li>tar: Extracts the contents of the tarball (compressed file).</li><li>mkdirp: A helper function to create directories recursively, provided in a separate file.</li></ul><h3>2: Fetching the Repository</h3><pre>export function fetch(url: string, dest: string) {<br>    return new Promise&lt;void&gt;((resolve, reject) =&gt; {<br>        https.get(url, (response) =&gt; {<br>            const code = response.statusCode as number;<br>            if (code &gt;= 400) {<br>                reject(<br>                    new Error(<br>                        `Network request to ${url} failed with code ${code} (${response.statusMessage})`,<br>                    ),<br>                );<br>            } else if (code &gt;= 300) {<br>                fetch(response.headers.location as string, dest)<br>                    .then(resolve)<br>                    .catch(reject);<br>            } else {<br>                response<br>                    .pipe(fs.createWriteStream(dest))<br>                    .on(&#39;finish&#39;, () =&gt; resolve())<br>                    .on(&#39;error&#39;, reject);<br>            }<br>        }).on(&#39;error&#39;, reject);<br>    });<br>}</pre><ul><li>URL Handling: The function checks if the request is successful (status codes below 300). If it’s a redirect (codes between 300 and 399), it follows the new URL. If it’s an error (codes 400+), it rejects the promise.</li><li>File Saving: The repository is downloaded and saved to the dest path using fs.createWriteStream.</li></ul><h3>3: Extracting the Repository</h3><p>After downloading the repository, it’s necessary to extract the contents of the tarball:</p><pre>function untar(file: string, dest: string) {<br>    return tar.extract(<br>        {<br>            file,<br>            strip: 1,<br>            C: dest,<br>        },<br>        [],<br>    );<br>}</pre><ul><li>Tar Extraction: This function extracts the contents of the .tar.gz file into the specified destination directory.</li></ul><h3>4: Putting It All Together</h3><p>The main degit function ties everything together, handling directory creation, fetching, and extracting the repository:</p><pre>export const degit = async ({<br>    repoOrg,<br>    repoName,<br>    dest,<br>}: {<br>    repoOrg: string;<br>    repoName: string;<br>    dest: string;<br>}) =&gt; {<br>    const base = path.join(tmpdir(), &#39;.degit&#39;);<br>    const dir = path.join(base, repoOrg, repoName);<br>    const file = `${dir}/HEAD.tar.gz`;<br>    const url = `https://github.com/${repoOrg}/${repoName}/archive/HEAD.tar.gz`;<br>    mkdirp(path.dirname(file));<br>    await fetch(url, file);<br>    mkdirp(dest);<br>    await untar(file, dest);<br>    fs.unlinkSync(file);<br>};</pre><p><a href="https://github.com/remotion-dev/remotion/blob/main/packages/create-video/src/mkdirp.ts">mkdirp</a> is used to create a directories recursively.</p><h3>Conclusion:</h3><p>I found that remotion uses degit to download templates when you run their installation commmand:</p><pre>npx create-video@latest</pre><p>This command asks you to choose a template, this is where degit comes into action to download the latest commit of the selected template</p><p>You can check this code from <a href="https://github.com/remotion-dev/remotion/blob/c535e676badd055187d1ea8007f9ac76ab0ad315/packages/create-video/src/init.ts#L109">create-video package</a> for proof.</p><figure><a href="https://app.thinkthroo.com/build-from-scratch"><img alt="" src="https://cdn-images-1.medium.com/max/800/0*7vT8QgWHKCJj4eCF" /></a></figure><blockquote><a href="https://app.thinkthroo.com/best-practices">Get free courses inspired by the best practices used in open source.</a></blockquote><h3>About me:</h3><p>Website: <a href="https://ramunarasinga.com/">https://ramunarasinga.com/</a></p><p>Linkedin: <a href="https://www.linkedin.com/in/ramu-narasinga-189361128/">https://www.linkedin.com/in/ramu-narasinga-189361128/</a></p><p>Github: <a href="https://github.com/Ramu-Narasinga">https://github.com/Ramu-Narasinga</a></p><p>Email: <a href="https://mailto:ramu.narasinga@gmail.com/">ramu.narasinga@gmail.com</a></p><p><a href="https://thinkthroo.com/">Learn the best practices used in open source.</a></p><h3>References:</h3><ol><li><a href="https://github.com/Rich-Harris/degit">https://github.com/Rich-Harris/degit</a></li><li><a href="https://github.com/remotion-dev/remotion/blob/main/packages/create-video/src/degit.ts">https://github.com/remotion-dev/remotion/blob/main/packages/create-video/src/degit.ts</a></li><li><a href="https://github.com/remotion-dev/remotion/blob/c535e676badd055187d1ea8007f9ac76ab0ad315/packages/create-video/src/init.ts#L109">https://github.com/remotion-dev/remotion/blob/c535e676badd055187d1ea8007f9ac76ab0ad315/packages/create-video/src/init.ts#L109</a></li><li><a href="https://github.com/remotion-dev/remotion/blob/main/packages/create-video/src/mkdirp.ts">https://github.com/remotion-dev/remotion/blob/main/packages/create-video/src/mkdirp.ts</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d2b628ac933" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supabase uses Valtio for its state management]]></title>
            <link>https://medium.com/@ramu.narasinga_61050/supabase-uses-valtio-for-its-state-management-1297a332e712?source=rss-3ddfc36c4e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/1297a332e712</guid>
            <category><![CDATA[valtio]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ramu Narasinga]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 22:12:36 GMT</pubDate>
            <atom:updated>2024-08-09T22:12:36.191Z</atom:updated>
            <content:encoded><![CDATA[<p>As I was reading the <a href="https://github.com/search?q=repo%3Asupabase%2Fsupabase+valtio&amp;type=code">Supabase source code</a> for “fun”, I came across a package named <a href="https://github.com/pmndrs/valtio">Valtio</a>.</p><p>I visited Valtio repository and found this in the description:</p><blockquote>💊 Valtio makes proxy-state simple for React and Vanilla</blockquote><p>In this article, we will look at:</p><ol><li>Proxy object.</li><li>Valtio usage with an example.</li><li>An example use case found in Supabase source code.</li></ol><h3>Proxy object</h3><p>Wait, what’s a Proxy? The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object. (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">From the MDN docs</a>). Valtio internally uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">Proxy</a> mechanism.</p><p>The below example is picked from MDN docs:</p><pre>// Example 1:<br>const target = {<br>  message1: &quot;hello&quot;,<br>  message2: &quot;everyone&quot;,<br>};<br><br>const handler1 = {};<br><br>const proxy1 = new Proxy(target, handler1);<br><br>console.log(proxy1.message1); // hello<br>console.log(proxy1.message2); // everyone<br><br>// Example 2:<br>const target = {<br>  message1: &quot;hello&quot;,<br>  message2: &quot;everyone&quot;,<br>};<br><br>const handler2 = {<br>  get(target, prop, receiver) {<br>    return &quot;world&quot;;<br>  },<br>};<br><br>const proxy2 = new Proxy(target, handler2);<br><br>console.log(proxy2.message1); // world<br>console.log(proxy2.message2); // world</pre><figure><a href="https://app.thinkthroo.com/course/json-write-spinner-cli/introduction/index?stepSlug=index&amp;type=index"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47EKz3q3aUidRrzxVGAjLg.png" /></a></figure><h3>Valtio usage with an example.</h3><p>The following demonstration is picked from the docs.</p><h4>Install</h4><pre>npm i valtio</pre><h4>Wrap your state object</h4><p>Valtio turns the object you pass it into a self-aware proxy.</p><pre>import { proxy, useSnapshot } from &#39;valtio&#39;<br>const state = proxy({ count: 0, text: &#39;hello&#39; })</pre><h4>Mutate from anywhere</h4><p>You can make changes to it in the same way you would to a normal js-object.</p><pre>setInterval(() =&gt; {<br>  ++state.count<br>}, 1000)</pre><h4>React via useSnapshot</h4><p>Create a local snapshot that catches changes. Rule of thumb: read from snapshots in render function, otherwise use the source. The component will only re-render when the parts of the state you access have changed, it is render-optimized.</p><pre>// This will re-render on `state.count` change but not on `state.text` change<br>function Counter() {<br>  const snap = useSnapshot(state)<br>  return (<br>    &lt;div&gt;<br>      {snap.count}<br>      &lt;button onClick={() =&gt; ++state.count}&gt;+1&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>An example use case found in Supabase source code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lViVcuZNxyffIgZ-zbtssw.png" /></figure><p>I searched long and hard to find a simple, easy to understand example use case in <a href="https://github.com/search?q=repo%3Asupabase%2Fsupabase+valtio&amp;type=code">Supabase source code</a>.</p><p>The example I picked is from <a href="https://github.com/supabase/supabase/blob/00385657e8da32535916969036bb4e76befc5a44/apps/studio/state/app-state.ts#L6">/apps/studio/state/app-state.ts</a></p><p>app-state.ts has about 95 lines of code at the time of writing this article.</p><pre>// pulled from https://github.com/supabase/supabase/blob/00385657e8da32535916969036bb4e76befc5a44/apps/studio/state/app-state.ts#L57-L60<br>showAiSettingsModal: false,<br>setShowAiSettingsModal: (value: boolean) =&gt; {<br>  appState.showAiSettingsModal = value<br>},</pre><p>showAiSettingsModal is found to be used in <a href="https://github.com/supabase/supabase/blob/00385657e8da32535916969036bb4e76befc5a44/apps/studio/components/ui/AISettingsModal.tsx#L20">/apps/studio/components/ui/AISettingsModal.tsx</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kx2xoUAi_t8iSPIEZMdjWw.png" /></figure><blockquote><a href="https://app.thinkthroo.com/best-practices">Get free courses inspired by the best practices used in open source.</a></blockquote><h3>About me:</h3><p>Website: <a href="https://ramunarasinga.com/">https://ramunarasinga.com/</a></p><p>Linkedin: <a href="https://www.linkedin.com/in/ramu-narasinga-189361128/">https://www.linkedin.com/in/ramu-narasinga-189361128/</a></p><p>Github: <a href="https://github.com/Ramu-Narasinga">https://github.com/Ramu-Narasinga</a></p><p>Email: ramu.narasinga@gmail.com</p><p><a href="https://thinkthroo.com/">Learn the best practices used in open source.</a></p><h3>References:</h3><ol><li><a href="https://github.com/search?q=repo%3Asupabase%2Fsupabase+valtio&amp;type=code">https://github.com/search?q=repo%3Asupabase%2Fsupabase+valtio&amp;type=code</a></li><li><a href="https://github.com/supabase/supabase/blob/00385657e8da32535916969036bb4e76befc5a44/apps/studio/state/app-state.ts#L6">https://github.com/supabase/supabase/blob/00385657e8da32535916969036bb4e76befc5a44/apps/studio/state/app-state.ts#L6</a></li><li><a href="https://github.com/search?q=repo%3Asupabase/supabase%20appState&amp;type=code">https://github.com/search?q=repo%3Asupabase/supabase%20appState&amp;type=code</a></li><li><a href="https://github.com/supabase/supabase/blob/00385657e8da32535916969036bb4e76befc5a44/apps/studio/components/ui/AISettingsModal.tsx#L20">https://github.com/supabase/supabase/blob/00385657e8da32535916969036bb4e76befc5a44/apps/studio/components/ui/AISettingsModal.tsx#L20</a></li><li><a href="https://github.com/pmndrs/valtio">https://github.com/pmndrs/valtio</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1297a332e712" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing the copyToClipboard implementations in Shadcn-ui/ui and Codehike.]]></title>
            <link>https://medium.com/@ramu.narasinga_61050/comparing-the-copytoclipboard-implementations-in-shadcn-ui-ui-and-codehike-80181dd626cc?source=rss-3ddfc36c4e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/80181dd626cc</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[codehike]]></category>
            <category><![CDATA[shadcn-ui]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ramu Narasinga]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 21:35:52 GMT</pubDate>
            <atom:updated>2024-08-11T13:57:29.561Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will compare the Copy button code between <a href="https://github.com/code-hike/codehike/blob/next/packages/mdx/src/smooth-code/copy-button.tsx#L3">Shadcn-ui/ui</a> and <a href="https://github.com/shadcn-ui/ui/blob/main/apps/www/components/copy-button.tsx#L31">Codehike</a>.</p><h3>copyToClipboard in Shadcn-ui/ui</h3><p>The code snippet below is picked from <a href="https://github.com/shadcn-ui/ui/blob/main/apps/www/components/copy-button.tsx#L24">shadcn-ui source code</a>.</p><pre>export async function copyToClipboardWithMeta(value: string, event?: Event) {<br>  navigator.clipboard.writeText(value)<br>  if (event) {<br>    trackEvent(event)<br>  }<br>}</pre><p>I think ‘withMeta’ in the function name copyToClipboardWithMeta refers to the analytics recorded in the <a href="https://github.com/shadcn-ui/ui/blob/main/apps/www/lib/events.ts#L27">trackEvent function</a>.</p><pre>import va from &quot;@vercel/analytics&quot;<br><br>export function trackEvent(input: Event): void {<br>  const event = eventSchema.parse(input)<br>  if (event) {<br>    va.track(event.name, event.properties)<br>  }<br>}</pre><h3>copyToClipboard in Codehike</h3><p>The code snippet below is picked from <a href="https://github.com/code-hike/codehike/blob/next/packages/mdx/src/smooth-code/copy-button.tsx#L54">codehike source code</a>.</p><pre>function copyToClipboard(text: string) {<br>  if (!navigator.clipboard) {<br>    fallbackCopyTextToClipboard(text)<br>    return<br>  }<br>  navigator.clipboard.writeText(text)<br>}</pre><p>Codehike implements the copyToClipboard differently.</p><ol><li>There is no analytics recorded when the copyToClipboard function is called like we saw this happening in Shadcn-ui/ui.</li><li>There is a fallback method in case the navigation.clipboard API is not available.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUnSWA5l9xkDQ4XC3Vp54w.png" /></figure><h4>fallbackCopyTextToClipboard:</h4><p>This below code snippet is picked from <a href="https://github.com/code-hike/codehike/blob/next/packages/mdx/src/smooth-code/copy-button.tsx#L62C1-L84C2">Codehike source code</a>. This function is just under the copyToClipboard.</p><pre>function fallbackCopyTextToClipboard(text: string) {<br>  var textArea = document.createElement(&quot;textarea&quot;)<br>  textArea.value = text<br><br>  // Avoid scrolling to bottom<br>  textArea.style.top = &quot;0&quot;<br>  textArea.style.left = &quot;0&quot;<br>  textArea.style.position = &quot;fixed&quot;<br><br>  document.body.appendChild(textArea)<br>  textArea.focus()<br>  textArea.select()<br><br>  try {<br>    var successful = document.execCommand(&quot;copy&quot;)<br>    // var msg = successful ? &quot;successful&quot; : &quot;unsuccessful&quot;<br>    // console.log(&quot;Fallback: Copying text command was &quot; + msg)<br>  } catch (err) {<br>    // console.error(&quot;Fallback: Oops, unable to copy&quot;, err)<br>  }<br><br>  document.body.removeChild(textArea)<br>}</pre><h3>Conclusion:</h3><p>If I were to implement a copyToClipboard functionality, I would also add a fallback in case the navigator.clipboard is not available in a given browser like in Codehike and if you also use Vercel analytics in your application, you might as well record your analytics like in shadcn-ui/ui.</p><figure><a href="https://app.thinkthroo.com/best-practices"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47EKz3q3aUidRrzxVGAjLg.png" /></a></figure><blockquote><a href="https://app.thinkthroo.com/best-practices">Get free courses inspired by the best practices used in open source.</a></blockquote><h3>About me:</h3><p>Website: <a href="https://ramunarasinga.com/">https://ramunarasinga.com/</a></p><p>Linkedin: <a href="https://www.linkedin.com/in/ramu-narasinga-189361128/">https://www.linkedin.com/in/ramu-narasinga-189361128/</a></p><p>Github: <a href="https://github.com/Ramu-Narasinga">https://github.com/Ramu-Narasinga</a></p><p>Email: ramu.narasinga@gmail.com</p><p><a href="https://thinkthroo.com/">Learn the best practices used in open source.</a></p><h3>References:</h3><ol><li><a href="https://github.com/code-hike/codehike/blob/next/packages/mdx/src/mini-editor/editor-tween.tsx">https://github.com/code-hike/codehike/blob/next/packages/mdx/src/mini-editor/editor-tween.tsx</a></li><li><a href="https://github.com/code-hike/codehike/blob/next/packages/mdx/src/smooth-code/copy-button.tsx#L3">https://github.com/code-hike/codehike/blob/next/packages/mdx/src/smooth-code/copy-button.tsx#L3</a></li><li><a href="https://github.com/shadcn-ui/ui/blob/main/apps/www/components/copy-button.tsx#L31">https://github.com/shadcn-ui/ui/blob/main/apps/www/components/copy-button.tsx#L31</a></li><li><a href="https://github.com/shadcn-ui/ui/blob/main/apps/www/components/copy-button.tsx#L24">https://github.com/shadcn-ui/ui/blob/main/apps/www/components/copy-button.tsx#L24</a></li><li><a href="https://github.com/shadcn-ui/ui/blob/main/apps/www/lib/events.ts#L27">https://github.com/shadcn-ui/ui/blob/main/apps/www/lib/events.ts#L27</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80181dd626cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shimmer effect in Card when you load Supabase dashboard.]]></title>
            <link>https://medium.com/@ramu.narasinga_61050/shimmer-effect-in-card-when-you-load-supabase-dashboard-216cf21fd2d7?source=rss-3ddfc36c4e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/216cf21fd2d7</guid>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css-animation]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ramu Narasinga]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 20:31:47 GMT</pubDate>
            <atom:updated>2024-08-11T13:56:56.091Z</atom:updated>
            <content:encoded><![CDATA[<p>When loading a dashboard, especially one as feature-rich as Supabase’s, it’s essential to provide visual feedback to users indicating that content is being loaded. A popular and visually appealing way to achieve this is by using a shimmer effect. This effect simulates a loading state and keeps users engaged while the actual content is being fetched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5qVmiFcIDkaIEnvA0tDwA.png" /></figure><p>Let’s explore how Supabase implements a shimmer effect in their dashboard using the animate property and some creative CSS.</p><h3>Shimmer Effect Using the Animate Property</h3><p>The <a href="https://github.com/supabase/supabase/blob/master/apps/studio/components/interfaces/Home/ProjectList/ShimmeringCard.tsx#L3">ShimmeringCard</a> component in Supabase&#39;s source code showcases how to create a shimmering loading effect using a combination of React and CSS animations.</p><p>Here’s the implementation of the ShimmeringCard component:</p><pre>// Pulled from <br>// https://github.com/supabase/supabase/blob/master/apps/studio/components/interfaces/Home/ProjectList/ShimmeringCard.tsx#L3<br>import CardButton from &#39;components/ui/CardButton&#39;<br><br>const ShimmeringCard = () =&gt; {<br>  return (<br>    &lt;CardButton<br>      className=&quot;h-44 !px-0 pt-5 pb-0&quot;<br>      title={<br>        &lt;div className=&quot;w-full justify-between space-y-1.5 px-5&quot;&gt;<br>          &lt;p className=&quot;flex-shrink truncate text-sm pr-4 shimmering-loader h-5 w-20&quot; /&gt;<br>          &lt;p className=&quot;text-sm lowercase text-foreground-light h-4 w-40 shimmering-loader&quot; /&gt;<br>        &lt;/div&gt;<br>      }<br>    /&gt;<br>  )<br>}<br>export default ShimmeringCard</pre><p>In this component, CardButton is used to create the card structure, and the shimmer effect is applied to the text elements within the card using the shimmering-loader class.</p><h3>The shimmering-loader CSS Class</h3><p>The <a href="https://github.com/supabase/supabase/blob/ce4213956045da0c174f4881b4300b508e30978c/apps/docs/styles/main.scss#L308C1-L317C2">shimmering-loader</a> class is defined in the <a href="https://github.com/supabase/supabase/blob/ce4213956045da0c174f4881b4300b508e30978c/apps/docs/styles/main.scss#L308C1-L317C2">main.scss</a> file and leverages the animate property to create the shimmer effect:</p><pre>.shimmering-loader {<br>  animation: shimmer 2s infinite linear;<br>  background: linear-gradient(<br>    to right,<br>    hsl(var(--border-default)) 4%,<br>    hsl(var(--background-surface-200)) 25%,<br>    hsl(var(--border-default)) 36%<br>  );<br>  background-size: 1000px 100%;<br>}</pre><h3>How It Works</h3><ol><li><strong>Animation Definition</strong>: The shimmer keyframes animation moves the background gradient from left to right.</li><li><strong>Gradient Background</strong>: The background is a linear gradient that creates the shimmer effect. The colors transition smoothly to give the appearance of a light moving across the surface.</li><li><strong>Animation Application</strong>: The shimmering-loader class applies this animation to any element, making it shimmer.</li></ol><figure><a href="https://app.thinkthroo.com/best-practices"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47EKz3q3aUidRrzxVGAjLg.png" /></a></figure><blockquote><a href="https://app.thinkthroo.com/best-practices">Get free courses inspired by the best practices used in open source.</a></blockquote><h3>About me:</h3><p>Website: <a href="https://ramunarasinga.com/">https://ramunarasinga.com/</a></p><p>Linkedin: <a href="https://www.linkedin.com/in/ramu-narasinga-189361128/">https://www.linkedin.com/in/ramu-narasinga-189361128/</a></p><p>Github: <a href="https://github.com/Ramu-Narasinga">https://github.com/Ramu-Narasinga</a></p><p>Email: ramu.narasinga@gmail.com</p><p><a href="https://thinkthroo.com/">Learn the best practices used in open source.</a></p><h3>References:</h3><ol><li><a href="https://github.com/supabase/supabase/blob/master/apps/studio/components/interfaces/Home/ProjectList/ShimmeringCard.tsx#L3">https://github.com/supabase/supabase/blob/master/apps/studio/components/interfaces/Home/ProjectList/ShimmeringCard.tsx#L3</a></li><li><a href="https://github.com/supabase/supabase/blob/ce4213956045da0c174f4881b4300b508e30978c/apps/docs/styles/main.scss#L308C1-L317C2">https://github.com/supabase/supabase/blob/ce4213956045da0c174f4881b4300b508e30978c/apps/docs/styles/main.scss#L308C1-L317C2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=216cf21fd2d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function overload in TypeScript]]></title>
            <link>https://medium.com/@ramu.narasinga_61050/function-overload-in-typescript-af69ec804210?source=rss-3ddfc36c4e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/af69ec804210</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[overload]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Ramu Narasinga]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 20:32:29 GMT</pubDate>
            <atom:updated>2024-08-11T13:56:10.291Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with TypeScript, you may encounter situations where a function needs to handle different types of input while maintaining type safety. This is where function overloading comes into play. Let’s look at a practical example of function overloading, inspired by a code snippet from the <a href="https://github.com/supabase/supabase/blob/master/apps/studio/hooks/misc/useIsFeatureEnabled.ts#L24">Supabase source code</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*834BLGxRg7Gwwb4YYAiPrQ.png" /></figure><h3>Example: useIsFeatureEnabled</h3><p>The <a href="https://github.com/supabase/supabase/blob/master/apps/studio/hooks/misc/useIsFeatureEnabled.ts#L24">useIsFeatureEnabled</a> function is a great example of function overloading. It can handle both an array of features and a single feature, returning appropriate results for each case.</p><p>Here’s the overloaded function definition:</p><pre>function useIsFeatureEnabled&lt;T extends Feature[]&gt;(<br>  features: T<br>): { [key in FeatureToCamelCase&lt;T[number]&gt;]: boolean }<br>function useIsFeatureEnabled(features: Feature): boolean<br>function useIsFeatureEnabled&lt;T extends Feature | Feature[]&gt;(features: T) {<br>  const { profile } = useProfile()<br><br>  if (Array.isArray(features)) {<br>      return Object.fromEntries(<br>        features.map((feature) =&gt; [<br>          featureToCamelCase(feature),<br>          checkFeature(feature, profile?.disabled_features),<br>        ])<br>      )<br>  }<br>  return checkFeature(features, profile?.disabled_features)<br>}<br>export { useIsFeatureEnabled }</pre><h3>How It Works</h3><ol><li><strong>Function Overloads</strong>: The first two declarations are overload signatures. They define the different ways the function can be called. The actual implementation comes last, handling both cases.</li><li><strong>Implementation</strong>: The function implementation checks if the input features is an array. If it is, it processes each feature, converts it to camelCase, and checks if it&#39;s enabled. If features is a single feature, it directly checks its status.</li></ol><h3>Supporting Functions and Types</h3><p>To understand this better, let’s look at the supporting checkFeature function and the type utility FeatureToCamelCase.</p><h4>checkFeature Function</h4><p>The checkFeature function determines if a given feature is enabled or not:</p><pre>function checkFeature(feature: Feature, features?: Feature[]) {<br>  return !features?.includes(feature) ?? true<br>}</pre><p>This function returns true if the feature is not in the disabled features list or if no disabled features are provided.</p><blockquote>Do watch the <a href="https://www.youtube.com/watch?v=Vr1BUFw6dJM">Matt Pocock’s Youtube video explanation</a> about the function overloads in TypeScript.</blockquote><h3>Conclusion</h3><p>Function overloading in TypeScript allows you to define multiple ways to call a function with different types of input while ensuring type safety. The useIsFeatureEnabled function from Supabase is an excellent example of this concept in action. It demonstrates how to handle different input types seamlessly, providing both flexibility and strong typing.</p><figure><a href="https://app.thinkthroo.com/best-practices"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47EKz3q3aUidRrzxVGAjLg.png" /></a></figure><blockquote><a href="https://app.thinkthroo.com/best-practices">Get free courses inspired by the best practices used in open source.</a></blockquote><h3>About me:</h3><p>Website: <a href="https://ramunarasinga.com/">https://ramunarasinga.com/</a></p><p>Linkedin: <a href="https://www.linkedin.com/in/ramu-narasinga-189361128/">https://www.linkedin.com/in/ramu-narasinga-189361128/</a></p><p>Github: <a href="https://github.com/Ramu-Narasinga">https://github.com/Ramu-Narasinga</a></p><p>Email: ramu.narasinga@gmail.com</p><p><a href="https://thinkthroo.com/">Learn the best practices used in open source.</a></p><h3>References:</h3><ol><li><a href="https://github.com/supabase/supabase/blob/master/apps/studio/hooks/misc/useIsFeatureEnabled.ts#L24">https://github.com/supabase/supabase/blob/master/apps/studio/hooks/misc/useIsFeatureEnabled.ts#L24</a></li><li><a href="https://www.youtube.com/watch?v=Vr1BUFw6dJM">Matt Pocock’s Youtube video explanation.</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af69ec804210" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert a string to camelCase using this function in Javascript.]]></title>
            <link>https://medium.com/@ramu.narasinga_61050/convert-a-string-to-camelcase-using-this-function-in-javascript-9ad111e20303?source=rss-3ddfc36c4e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ad111e20303</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[camel-case]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ramu Narasinga]]></dc:creator>
            <pubDate>Wed, 31 Jul 2024 20:32:29 GMT</pubDate>
            <atom:updated>2024-08-11T13:55:31.651Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever needed to convert a string to camelCase? I found an interesting code snippet while exploring the open-source <a href="https://github.com/supabase/supabase/blob/master/apps/studio/hooks/misc/useIsFeatureEnabled.ts#L16">Supabase repository</a>. Here’s the method they use:</p><pre>function featureToCamelCase(feature: Feature) {<br>  return feature<br>    .replace(/:/g, &#39;_&#39;)<br>    .split(&#39;_&#39;)<br>    .map((word, index) =&gt; (index === 0 ? word : word[0].toUpperCase() + word.slice(1)))<br>    .join(&#39;&#39;) as FeatureToCamelCase&lt;typeof feature&gt;<br>}</pre><p>This function is pretty neat. It replaces colons with underscores, splits the string into words, and then maps through each word to convert it to camelCase. The first word is kept in lowercase, and the subsequent words have their first character capitalized before being joined back together. Simple yet effective!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vlc1Hh_zkfO6TsdqUQEEog.png" /></figure><p>I came across another approach on Stack Overflow that doesn’t use regular expressions. Here’s the alternative:</p><pre>function toCamelCase(str) {<br>  return str.split(&#39; &#39;).map(function(word, index) {<br>    // If it is the first word make sure to lowercase all the chars.<br>    if (index == 0) {<br>      return word.toLowerCase();<br>    }<br>    // If it is not the first word only upper case the first char and lowercase the rest.<br>    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();<br>  }).join(&#39;&#39;);<br>}</pre><p>This <a href="https://stackoverflow.com/a/35976812">code snippet from SO </a>has comments explaining what this code does except it does not use any sort of regex. The code found in Supabase’s way of converting a string to camelCase is very similar to this <a href="https://stackoverflow.com/a/35976812">SO answer</a>, except for the comments and the regex used.</p><pre>.replace(/:/g, &#39;_&#39;)</pre><p>This method splits the string by spaces and then maps over each word. The first word is entirely lowercased, while the subsequent words are capitalized at the first character and lowercased for the rest. Finally, the words are joined back together to form a camelCase string.</p><p>One interesting comment from a Stack Overflow user mentioned the performance advantage of this approach:</p><blockquote><em>“+1 for not using regular expressions, even if the question asked for a solution using them. This is a much clearer solution, and also a clear win for performance (because processing complex regular expressions is a much harder task than just iterating over a bunch of strings and joining bits of them together). See jsperf.com/camel-casing-regexp-or-character-manipulation/1 where I’ve taken some of the examples here along with this one (and also my own modest improvement of it for performance, although I would probably prefer this version for clarity’s sake in most cases).”</em></blockquote><p>Both methods have their merits. The regex approach in the Supabase code is concise and leverages powerful string manipulation techniques. On the other hand, the non-regex approach is praised for its clarity and performance, as it avoids the computational overhead associated with regular expressions.</p><p>Here’s how you can choose between them:</p><ul><li><strong>Use the regex approach</strong> if you need a compact, one-liner solution that leverages JavaScript’s powerful regex capabilities. Also be sure to add comments explaining what your regex does, so that your future self or next dev working with your code can understand.</li><li><strong>Opt for the non-regex method</strong> if you prioritize readability and performance, especially when dealing with longer strings or running this conversion multiple times.</li></ul><figure><a href="https://app.thinkthroo.com/best-practices"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47EKz3q3aUidRrzxVGAjLg.png" /></a></figure><blockquote><a href="https://app.thinkthroo.com/best-practices">Get free courses inspired by the best practices used in open source.</a></blockquote><h3>About me:</h3><p>Website: <a href="https://ramunarasinga.com/">https://ramunarasinga.com/</a></p><p>Linkedin: <a href="https://www.linkedin.com/in/ramu-narasinga-189361128/">https://www.linkedin.com/in/ramu-narasinga-189361128/</a></p><p>Github: <a href="https://github.com/Ramu-Narasinga">https://github.com/Ramu-Narasinga</a></p><p>Email: ramu.narasinga@gmail.com</p><p><a href="https://thinkthroo.com/">Learn the best practices used in open source.</a></p><h3>References:</h3><ol><li><a href="https://github.com/supabase/supabase/blob/master/apps/studio/hooks/misc/useIsFeatureEnabled.ts#L16">https://github.com/supabase/supabase/blob/master/apps/studio/hooks/misc/useIsFeatureEnabled.ts#L16</a></li><li><a href="https://stackoverflow.com/a/35976812">https://stackoverflow.com/a/35976812</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ad111e20303" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparison of file and component structures among Shadcn-ui, Plane.so and Gitroom.]]></title>
            <link>https://blog.devgenius.io/comparison-of-next-js-file-and-component-structures-among-shadcn-ui-plane-so-and-gitroom-70715b42d391?source=rss-3ddfc36c4e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/70715b42d391</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[shadcn-ui]]></category>
            <category><![CDATA[structure]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Ramu Narasinga]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 20:31:39 GMT</pubDate>
            <atom:updated>2024-08-11T13:54:57.513Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will look at folder structures in Shadcn-ui, Plane.so and Gitroom used to organise a Next.js project.</p><h3>Shadcn-ui file and component structures:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCqjxDyfuMNk-GmBPj-t4g.png" /></figure><h4>File structure</h4><p><a href="https://github.com/shadcn-ui/ui/blob/main/apps/www/app/(app)/examples/dashboard/page.tsx">Shadcn-ui/ui</a> uses app router and has a <a href="https://github.com/shadcn-ui/ui/tree/main/apps/www/app/(app)">Router group named (app)</a>.</p><p>In the (app) folder, you will find a folder with page.tsx and/or layout.tsx in some routes such as <a href="https://github.com/shadcn-ui/ui/tree/main/apps/www/app/(app)/colors">colors</a>, <a href="https://github.com/shadcn-ui/ui/tree/main/apps/www/app/(app)/blocks">blocks</a>, <a href="https://github.com/shadcn-ui/ui/tree/main/apps/www/app/(app)/docs">docs</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*cK-HH4G8egQoW9YljjvC8w.png" /></figure><h4>Component structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*_Qy97sLxno32IYajJEOFog.png" /></figure><p>In <a href="https://github.com/shadcn-ui/ui/blob/main/apps/www/app/(app)/blocks/page.tsx">blocks/page.tsx</a>, you will find that it imports components that are generic or that can be reused in other pages.</p><p>But wait, there’s other kind of components.</p><p>If you look at <a href="https://github.com/shadcn-ui/ui/tree/main/apps/www/app/(app)/examples">examples route</a>, each example has its own component that is specific to an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*uxEJQYKxq_75VeduDBsacw.png" /></figure><p>so there’s components available at <a href="https://github.com/shadcn-ui/ui/tree/main/apps/www/app/(app)/examples/cards/components">examples/card/components</a> and then there are also <a href="https://github.com/shadcn-ui/ui/tree/main/apps/www/components">generic components</a> that can be reused.</p><h3>Plane.so file and component structures:</h3><p><a href="https://github.com/makeplane/plane/tree/preview">plane.so</a> has similar structure to that shadcn-ui/ui where you will find components specific to features by their names as shown below.</p><h4>File structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJCDz83kmZevh91TErHNAw.png" /></figure><p>The file structure in <a href="https://plane.so/">plane.so</a> uses nested routes but it does have a header.tsx specific to a route defined in all the folders along with page.tsx or layout.tsx</p><h4>Component structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_TgRfFwPFkbXYC5Wbw8Kw.png" /></figure><p>All the components used in the app router are placed inside <a href="https://github.com/makeplane/plane/tree/preview/web/core">core folder</a>.</p><p>So now comes the question, how come we see the imports as “@/components” in a router as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SEr4u4d9ckp2s7TuEJ9t7A.png" /></figure><p>when there is no components folder at app folder level:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*DbYeDx_b3hK6eyDYg7tSCg.png" /></figure><p>Well, the components are inside core folder and tsconfig.json has the paths defined to locate the folders in core as base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtGvBiOrJOqvRg7igslhFg.png" /></figure><h3>Gitroom file and component structures:</h3><p>Gitroom has a straight forward structure. Routes have page.tsx and each page.tsx uses components from components folder and this components folder contains files specific to features.</p><h4>File structure:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOM1G3JZiWbRDfsCYc0gbQ.png" /></figure><p>As you can see, router only has one file name page.tsx and that’s it. We see in shadcn-ui where it contains components specific to a route that are scoped to that route, similarly in plane.so, it has route specific header.tsx along with page.tsx however, one commonality in all of these projects is that there is a components folder that can be reused or specific to a feature depending on the folder name.</p><h4>Component structure:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EtGQ4CdVtOy25qsu5zluiw.png" /></figure><p>Notice how the route/file structures has the folder names that match with some of the folders names in component structure.</p><figure><a href="https://app.thinkthroo.com/best-practices"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47EKz3q3aUidRrzxVGAjLg.png" /></a></figure><blockquote><a href="https://app.thinkthroo.com/best-practices">Get free courses inspired by the best practices used in open source.</a></blockquote><h3>About me:</h3><p>Website: <a href="https://ramunarasinga.com/">https://ramunarasinga.com/</a></p><p>Linkedin: <a href="https://www.linkedin.com/in/ramu-narasinga-189361128/">https://www.linkedin.com/in/ramu-narasinga-189361128/</a></p><p>Github: <a href="https://github.com/Ramu-Narasinga">https://github.com/Ramu-Narasinga</a></p><p>Email: ramu.narasinga@gmail.com</p><p><a href="https://thinkthroo.com/">Learn the best practices used in open source.</a></p><h3>References:</h3><ol><li><a href="https://github.com/shadcn-ui/ui/tree/main/apps/www/app/(app)/examples/cards/components">https://github.com/shadcn-ui/ui/tree/main/apps/www/app/(app)/examples/cards/components</a></li><li><a href="https://github.com/makeplane/plane/tree/preview">https://github.com/makeplane/plane/tree/preview</a></li><li><a href="https://github.com/gitroomhq/gitroom/blob/main/apps/frontend/src/app/(site)/launches/page.tsx">https://github.com/gitroomhq/gitroom/blob/main/apps/frontend/src/app/(site)/launches/page.tsx</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70715b42d391" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/comparison-of-next-js-file-and-component-structures-among-shadcn-ui-plane-so-and-gitroom-70715b42d391">Comparison of file and component structures among Shadcn-ui, Plane.so and Gitroom.</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cache your fetcher in useSWR with useCallback.]]></title>
            <link>https://medium.com/@ramu.narasinga_61050/cache-your-fetcher-in-useswr-with-usecallback-c2160bd3af7c?source=rss-3ddfc36c4e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2160bd3af7c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[useswr]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ramu Narasinga]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 20:32:27 GMT</pubDate>
            <atom:updated>2024-08-11T13:54:28.080Z</atom:updated>
            <content:encoded><![CDATA[<p>I found a way that caches the fetcher in useSWR using useCallback in the <a href="https://github.com/search?q=repo%3Agitroomhq%2Fgitroom%20useSWR&amp;type=code">Gitroom source code</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dCWMweVkRrqIuMzopjS7g.png" /></figure><p>The above image is from <a href="https://github.com/gitroomhq/gitroom/blob/c03b96215fa30b267a97d7eafc2281f482a3192f/apps/frontend/src/components/platform-analytics/render.analytics.tsx#L25">platform-analytics/render.analytics.tsx</a>. Let’s try to understand this code snippet.</p><p>we’ll explore how to optimize data fetching in your React applications using the useCallback hook in combination with useSWR. We&#39;ll break down the provided code snippet, explain why caching your fetcher function is important.</p><h4>Understanding the Code</h4><p>Let’s dive into the code step by step:</p><pre>const load = useCallback(async () =&gt; {<br>  setLoading(true);<br>  const load = (<br>    await fetch(`/analytics/${integration.id}?date=${date}`)<br>  ).json();<br>  setLoading(false);<br>  return load;<br>}, [integration, date]);</pre><p>Here, we’re defining an asynchronous function load inside a useCallback hook. This function fetches data from a specified endpoint and handles the loading state. The useCallback hook ensures that this function is memoized and only recreated when the dependencies (integration and date) change.</p><p>Next, we use useSWR to manage the data fetching:</p><pre>const { data } = useSWR(`/analytics-${integration?.id}-${date}`, load, {<br>  refreshInterval: 0,<br>  refreshWhenHidden: false,<br>  revalidateOnFocus: false,<br>  revalidateOnReconnect: false,<br>  revalidateIfStale: false,<br>  refreshWhenOffline: false,<br>  revalidateOnMount: true,<br>});</pre><p>Here, useSWR is configured with a key (/analytics-${integration?.id}-${date}) and our memoized load function. The configuration options control the revalidation behavior of the data.</p><h3>How useCallback Prevents Unnecessary Re-fetches</h3><p>To understand how useCallback prevents unnecessary re-fetches, we need to delve into how React handles function references and how useSWR works.</p><h4>Function References in React</h4><p>In React, every time a component re-renders, all functions defined within it are recreated. This means that without useCallback, a new instance of your load function would be created on every render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6evtFxMNVvHjLsFXKVySQ.png" /></figure><h4>Impact on useSWR</h4><p>useSWR is a data fetching library for React. It uses a key to identify the data and a fetcher function to fetch it. useSWR relies on the stability of the fetcher function reference. If the reference changes, useSWR might interpret this as a signal that the data needs to be refetched, even if the actual logic of the fetcher hasn&#39;t changed.</p><p>Here’s a detailed explanation:</p><ol><li><strong>Without </strong><strong>useCallback</strong>:</li></ol><pre>const load = async () =&gt; {<br>  setLoading(true);<br>  const load = (<br>    await fetch(`/analytics/${integration.id}?date=${date}`)<br>  ).json();<br>  setLoading(false);<br>  return load;<br>};<br><br>const { data } = useSWR(`/analytics-${integration?.id}-${date}`, load, {<br>  refreshInterval: 0,<br>  refreshWhenHidden: false,<br>  revalidateOnFocus: false,<br>  revalidateOnReconnect: false,<br>  revalidateIfStale: false,<br>  refreshWhenOffline: false,<br>  revalidateOnMount: true,<br>});</pre><p>In this case, every render creates a new load function. useSWR sees a different function reference each time, which can lead to unnecessary re-fetches even when integration and date haven&#39;t changed.</p><p><strong>With </strong><strong>useCallback</strong>:</p><pre>const load = useCallback(async () =&gt; {<br>  setLoading(true);<br>  const load = (<br>    await fetch(`/analytics/${integration.id}?date=${date}`)<br>  ).json();<br>  setLoading(false);<br>  return load;<br>}, [integration, date]);<br><br>const { data } = useSWR(`/analytics-${integration?.id}-${date}`, load, {<br>  refreshInterval: 0,<br>  refreshWhenHidden: false,<br>  revalidateOnFocus: false,<br>  revalidateOnReconnect: false,<br>  revalidateIfStale: false,<br>  refreshWhenOffline: false,<br>  revalidateOnMount: true,<br>});</pre><p>By wrapping the load function in useCallback, we ensure that it is only recreated when its dependencies (integration and date) change. This stability in the function reference tells useSWR that the fetcher function hasn&#39;t changed unless integration or date changes, thus preventing unnecessary re-fetches.</p><figure><a href="https://app.thinkthroo.com/best-practices"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47EKz3q3aUidRrzxVGAjLg.png" /></a></figure><blockquote><a href="https://app.thinkthroo.com/best-practices">Get free courses inspired by the best practices used in open source.</a></blockquote><h3>About me:</h3><p>Website: <a href="https://ramunarasinga.com/">https://ramunarasinga.com/</a></p><p>Linkedin: <a href="https://www.linkedin.com/in/ramu-narasinga-189361128/">https://www.linkedin.com/in/ramu-narasinga-189361128/</a></p><p>Github: <a href="https://github.com/Ramu-Narasinga">https://github.com/Ramu-Narasinga</a></p><p>Email: ramu.narasinga@gmail.com</p><p><a href="https://thinkthroo.com/">Learn the best practices used in open source.</a></p><h3>References:</h3><ol><li><a href="https://github.com/gitroomhq/gitroom/blob/c03b96215fa30b267a97d7eafc2281f482a3192f/apps/frontend/src/components/platform-analytics/render.analytics.tsx#L25">https://github.com/gitroomhq/gitroom/blob/c03b96215fa30b267a97d7eafc2281f482a3192f/apps/frontend/src/components/platform-analytics/render.analytics.tsx#L25</a></li><li><a href="https://github.com/search?q=repo%3Agitroomhq%2Fgitroom%20useSWR&amp;type=code">https://github.com/search?q=repo%3Agitroomhq%2Fgitroom%20useSWR&amp;type=code</a></li><li><a href="https://swr.vercel.app/docs/getting-started">https://swr.vercel.app/docs/getting-started</a></li><li><a href="https://react.dev/reference/react/useCallback">https://react.dev/reference/react/useCallback</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2160bd3af7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using a custom backend server with Next.js in a monorepo.]]></title>
            <link>https://medium.com/@ramu.narasinga_61050/using-a-custom-backend-server-with-next-js-in-a-monorepo-b650e8ab8608?source=rss-3ddfc36c4e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/b650e8ab8608</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ramu Narasinga]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 20:41:11 GMT</pubDate>
            <atom:updated>2024-08-11T13:53:41.634Z</atom:updated>
            <content:encoded><![CDATA[<p>I was searching for an open source repository that schedules and posts on social media. I found <a href="https://github.com/gitroomhq/gitroom/tree/main">Gitroom</a>.</p><p>Gitroom is a awesome, built by <a href="https://github.com/nevo-david">Nevo David</a>. You can 📨 schedule social media and articles. Exchange or buy posts from other members 👨🏻‍💻. Monitor your GitHub trending, and so much more 📈.</p><p>The following are some interesting things I learnt from this <a href="https://github.com/gitroomhq/gitroom/tree/main">repository</a></p><p>1. You can use your own backend with Next.js<br>2. A note about customFetch <br>3. The way the files are named.</p><h3>1. You can use your own backend with Next.js</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*8TB1LUyhDqT-usAkFmwAzQ.png" /></figure><p>Gitroom uses the following tech stack:</p><ul><li>NX (Monorepo)</li><li>NextJS (React)</li><li>NestJS</li><li>Prisma (Default to PostgreSQL)</li><li>Redis</li><li>Resend (emails notifications)</li></ul><p>It has folders named as frontend, backend, cron etc.,</p><p>I wondered for quite some time now, if we could use our own backend when you are already using the Next.js, a “full stack” react framework but, I kept seeing people advising to use your custom backend when you need advanced features like cron, web sockets etc., on Reddit. <br> <br>Now that I found Gitroom that demonstrates the custom backend usage along with Next.js and cron, I have a good feeling that you could learn some advanced patterns studying this repository.</p><h3>2. A note about customFetch</h3><p>The following code snippet is picked from <a href="https://github.com/gitroomhq/gitroom/blob/e7b669f1253e3ef7ae6b9cc9d2f1d529ea86b288/apps/frontend/src/app/(site)/settings/page.tsx#L21">apps/frontend/src/app/(site)/settings/page.tsx#L21</a></p><pre>if (searchParams.code) {<br>  await internalFetch(&#39;/settings/github&#39;, {<br>  method: &#39;POST&#39;,<br>  body: JSON.stringify({ code: searchParams.code }),<br>  });<br>  <br>  return redirect(&#39;/settings&#39;, RedirectType.replace);<br>}</pre><p>‘internalFetch’ uses customFetch.</p><p>The below code snippet is picked from <a href="https://github.com/gitroomhq/gitroom/blob/e7b669f1253e3ef7ae6b9cc9d2f1d529ea86b288/libraries/helpers/src/utils/custom.fetch.func.ts#L10">libraries/helpers/src/utils/custom.fetch.func.ts</a></p><pre>export const customFetch = (<br> params: Params,<br> auth?: string,<br> showorg?: string<br> ) =&gt; {<br> return async function newFetch(url: string, options: RequestInit = {}) {<br>   const newRequestObject = await params?.beforeRequest?.(url, options);<br>   const fetchRequest = await fetch(params.baseUrl + url, {<br>   credentials: &#39;include&#39;,<br>   …(newRequestObject || options),<br>   headers: {<br>   …(auth ? { auth } : {}),<br>   …(showorg ? { showorg } : {}),<br>   …(options.body instanceof FormData<br>   ? {}<br>   : { &#39;Content-Type&#39;: &#39;application/json&#39; }),<br>   Accept: &#39;application/json&#39;,<br>   …options?.headers,<br>   },<br>   // @ts-ignore<br>   …(!options.next &amp;&amp; options.cache !== &#39;force-cache&#39;<br>   ? { cache: options.cache || &#39;no-store&#39; }<br>   : {}),<br> });<br><br>if (<br> !params?.afterRequest ||<br> (await params?.afterRequest?.(url, options, fetchRequest))<br> ) {<br>   return fetchRequest;<br> }<br>// @ts-ignore<br>   return new Promise((res) =&gt; {}) as Response;<br>   };<br>};</pre><p>Why???, I don’t know the answer yet but, I can tell there is “beforeRequest” and “afterRequest” processing happening based on the above code snippet</p><h3>3. The way the files are named.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*ienhHi1o5R89ivR7Xgtf6A.png" /></figure><p>I have never seen a service file named using dots like “custom.fetch.func.ts”. Sure, there’s config files named as tailwind.config.ts etc.,</p><p>Here’s what chatGPT has to say about this:<br> “<br> This kind of naming does not fit into a traditional case style like snake_case, kebab-case, or camelCase.</p><p>However, if we ignore the file extension (“.ts”) and consider only “custom.fetch.func,” it can be seen as:</p><p>Dot notation: This isn’t a standard case style but is sometimes used in programming to represent a hierarchical relationship or to namespace parts of a name.<br> “</p><p>To be honest, choose w/e naming conventions work for you. I use lowercase words separated by dashes as a file name, like custom-fetch-func.ts</p><figure><a href="https://app.thinkthroo.com/best-practices"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47EKz3q3aUidRrzxVGAjLg.png" /></a></figure><blockquote><a href="https://app.thinkthroo.com/best-practices">Get free courses inspired by the best practices used in open source.</a></blockquote><h3>About me:</h3><p>Website: <a href="https://ramunarasinga.com/">https://ramunarasinga.com/</a></p><p>Linkedin: <a href="https://www.linkedin.com/in/ramu-narasinga-189361128/">https://www.linkedin.com/in/ramu-narasinga-189361128/</a></p><p>Github: <a href="https://github.com/Ramu-Narasinga">https://github.com/Ramu-Narasinga</a></p><p>Email: ramu.narasinga@gmail.com</p><p><a href="https://thinkthroo.com/">Learn the best practices used in open source.</a></p><h3>Resources:</h3><p>1. https://github.com/gitroomhq/gitroom/blob/e7b669f1253e3ef7ae6b9cc9d2f1d529ea86b288/libraries/helpers/src/utils/internal.fetch.ts#L4</p><p><a href="https://github.com/gitroomhq/gitroom/blob/e7b669f1253e3ef7ae6b9cc9d2f1d529ea86b288/libraries/helpers/src/utils/custom.fetch.func.ts#L10">gitroom/libraries/helpers/src/utils/custom.fetch.func.ts at e7b669f1253e3ef7ae6b9cc9d2f1d529ea86b288 · gitroomhq/gitroom</a></p><p><a href="https://github.com/gitroomhq/gitroom/tree/main">2. https://github.com/gitroomhq/gitroom/tree/main</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b650e8ab8608" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[shadcn-ui/ui codebase analysis: How does shadcn-ui CLI work? — Part 3.1]]></title>
            <link>https://medium.com/@ramu.narasinga_61050/shadcn-ui-ui-codebase-analysis-how-does-shadcn-ui-cli-work-part-3-1-834007e6f0b2?source=rss-3ddfc36c4e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/834007e6f0b2</guid>
            <category><![CDATA[shadcn]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ramu Narasinga]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 20:32:27 GMT</pubDate>
            <atom:updated>2024-08-11T13:52:49.117Z</atom:updated>
            <content:encoded><![CDATA[<h3>shadcn-ui/ui codebase analysis: How does shadcn-ui CLI work? — Part 3.1</h3><p>I wanted to find out how shadcn-ui CLI works. In this article, I discuss the code used to build the shadcn-ui/ui CLI.</p><p>In part 3.0, I discussed how `npx shadcn-ui add &lt;component&gt;` command is registered. We will look at few more lines of code from <a href="https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/commands/add.ts">packages/cli/src/commands/add.ts</a>.</p><pre>const cwd = path.resolve(options.cwd)<br><br>if (!existsSync(cwd)) {<br>  logger.error(`The path ${cwd} does not exist. Please try again.`)<br>  process.exit(1)<br>}<br><br>const config = await getConfig(cwd)<br>if (!config) {<br>  logger.warn(<br>    `Configuration is missing. Please run ${chalk.green(<br>      `init`<br>    )} to create a components.json file.`<br>  )<br>  process.exit(1)<br>}<br><br>const registryIndex = await getRegistryIndex()</pre><p>So what’s happening in the above code snippet?</p><ol><li>Check if the cwd exists.</li><li>getConfig function.</li><li>getRegistryIndex.</li></ol><h3>Check if the cwd exists.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*c0e0rOoYv2VJrgJzV1zWKA.png" /></figure><p>This code checks the current directory exists and logs an error if it doesn’t.</p><p>existsSync is imported from “fs” at the top of add.ts file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tbQEPNA3ResO2mGwxc4tyQ.png" /></figure><h3>getConfig function</h3><p>getConfig is not as simple as it looks like.</p><pre>const config = await getConfig(cwd)<br>if (!config) {<br>  logger.warn(<br>    `Configuration is missing. Please run ${chalk.green(<br>      `init`<br>    )} to create a components.json file.`<br>  )<br>  process.exit(1)<br>}</pre><p>`getConfig` is imported from a different file named <a href="https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/get-config.ts#L55">get-config</a>. Reason behind this could be that context matters when it comes where you place your function. For example, logically, a function named `getConfig` can never be placed in a file named `get-project-info`.</p><pre>export async function getConfig(cwd: string) {<br>  const config = await getRawConfig(cwd)<br><br>  if (!config) {<br>    return null<br>  }<br><br>  return await resolveConfigPaths(cwd, config)<br>}</pre><p>This function calls another function named `getRawConfig`.</p><p>I explained in great detail how getConfig works in the article <a href="https://medium.com/@ramu.narasinga_61050/shadcn-ui-ui-codebase-analysis-how-does-shadcn-ui-cli-work-part-2-2-73cff5651b06">Part 2.2</a></p><h3>getRegistryIndex</h3><pre>export async function getRegistryIndex() {<br>  try {<br>    const [result] = await fetchRegistry([&quot;index.json&quot;])<br><br>    return registryIndexSchema.parse(result)<br>  } catch (error) {<br>    throw new Error(`Failed to fetch components from registry.`)<br>  }<br>}</pre><p>A simple utility function that fetches index.json available at <a href="https://ui.shadcn.com/registry/index.json">https://ui.shadcn.com/registry/index.json</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*q0T-WVyOC-kp2G3pKdK6ZQ.png" /></figure><h3>Conclusion:</h3><p>Once the options and the argument passed to add command in shadcn-ui CLI, In the action, there is a lot of code, about 218 lines in <a href="https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/commands/add.ts#L1">add.ts</a>. I picked a few lines of code that followed part 3.0 explanation and discussed about</p><ol><li>Check if the cwd exists.</li></ol><p>This code checks the current directory exists and logs an error if it doesn’t.</p><p>existsSync is imported from “fs” at the top of add.ts file.</p><p>2. getConfig function.</p><p>`getConfig` is imported from a different file named <a href="https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/get-config.ts#L55">get-config</a>. Reason behind this could be that context matters when it comes where you place your function. For example, logically, a function named `getConfig` can never be placed in a file named `get-project-info`.</p><p>I explained in great detail how getConfig works in the article <a href="https://medium.com/@ramu.narasinga_61050/shadcn-ui-ui-codebase-analysis-how-does-shadcn-ui-cli-work-part-2-2-73cff5651b06">Part 2.2</a></p><p>3. getRegistryIndex.</p><p>A simple utility function that fetches index.json available at <a href="https://ui.shadcn.com/registry/index.json">https://ui.shadcn.com/registry/index.json</a></p><figure><a href="https://app.thinkthroo.com/best-practices"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47EKz3q3aUidRrzxVGAjLg.png" /></a></figure><blockquote><a href="https://app.thinkthroo.com/best-practices">Get free courses inspired by the best practices used in open source.</a></blockquote><h3>About me:</h3><p>Website: <a href="https://ramunarasinga.com/">https://ramunarasinga.com/</a></p><p>Linkedin: <a href="https://www.linkedin.com/in/ramu-narasinga-189361128/">https://www.linkedin.com/in/ramu-narasinga-189361128/</a></p><p>Github: <a href="https://github.com/Ramu-Narasinga">https://github.com/Ramu-Narasinga</a></p><p>Email: ramu.narasinga@gmail.com</p><p><a href="https://thinkthroo.com/">Learn the best practices used in open source.</a></p><h3>References:</h3><ol><li><a href="https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/commands/add.ts">https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/commands/add.ts</a></li><li><a href="https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/get-config.ts#L55">https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/get-config.ts#L55</a></li><li><a href="https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/get-config.ts#L91">https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/get-config.ts#L91</a></li><li><a href="https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/registry/index.ts#L19C1-L27C2">https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/registry/index.ts#L19C1-L27C2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=834007e6f0b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>