<?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 Nick Grato on Medium]]></title>
        <description><![CDATA[Stories by Nick Grato on Medium]]></description>
        <link>https://medium.com/@ngrato?source=rss-f3fc76aef1e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rWbrBVsfoqRHfXBlG8sJkA.jpeg</url>
            <title>Stories by Nick Grato on Medium</title>
            <link>https://medium.com/@ngrato?source=rss-f3fc76aef1e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 22:55:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ngrato/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 Art of Prompting : Mastering Large Language Models]]></title>
            <link>https://medium.com/@ngrato/the-art-of-prompting-01249e5f05ae?source=rss-f3fc76aef1e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/01249e5f05ae</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ai-prompt-writer]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Nick Grato]]></dc:creator>
            <pubDate>Fri, 03 May 2024 17:34:42 GMT</pubDate>
            <atom:updated>2024-05-03T17:37:01.371Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNQ3DC2MKBC3ZgMWYAMA6Q.png" /><figcaption>Prompt Artist</figcaption></figure><p>I think my first experience with LLMs ( Large Language Models) was similar to most. I asked it funny questions and told it to tell me stories in the style of Ace Ventura. I quickly realized the power of AI, but other than asking a few quick one liners in the chat box I never really knew what else I could accomplish with this Wizard of Oz like power. Once I started understanding the landscape a little more I realized there is an art to writing prompts. I’d like to share a few things I picked up along the way. I’m still new in this journey but hopefully these tools will help you along yours.</p><h4>Creating the perfect prompt</h4><p>Spoiler, there is no perfect prompt. If your question is somewhat basic, a simple fact or a straightforward &lt;code&gt; inquiry you probably won’t find what you are looking for right away. The path to perfection is in fact through the use of <em>many</em> prompts. What I mean is — prompting a model and then prompting it again on the information and the context of the entire conversation and repeating this until you get the desired output.</p><p>At <a href="https://formulaic.app/">Formulaic.app</a> you are able to create a number of prompts in a row to create one entire sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stEGlp5WVldMMKeZUtMs5g.png" /></figure><p>At first glance this can seem like you are just creating a conversation with a model, in actuality the result of the chain of prompts is much more polished than if this was a single prompt.</p><p>For example in the screen shot above where I spelt grammatical ironically wrong I used LLM Model Llama 2–13B with a chain of prompts and again with a all the same text as a single prompt. Here’s an example plot generated by a single prompt.</p><p><em>Plot Line:<br>In the midst of World War II, a brilliant scientist named Dr. Emma Taylor invents a time machine that allows her to travel through the ages. When she discovers a way to communicate with her past and future selves, she must navigate the complexities of time travel and confront the consequences of her actions.</em></p><p>Not bad, but not great. Here is the plot line from the prompt chain, again with the same text but broken up in a sequence.</p><p><em>Plot Preview:</em></p><p><em>In the midst of World War II, a group of brilliant scientists at Columbia University stumble upon a groundbreaking discovery that could change the course of human history. Led by the fearless and ambitious Dr. Evelyn Fox, the team of researchers uncover a way to harness the power of quantum entanglement to manipulate matter and energy at unprecedented levels.</em></p><p><em>As they delve deeper into their research, the team realizes the immense implications of their discovery. With the potential to create limitless energy, control the weather, and even manipulate the fabric of reality itself, the team must navigate the treacherous waters of government conspiracies, corporate greed, and the ethical dilemmas of playing god.</em></p><p><em>But as they race against time to perfect their invention, the team members begin to uncover dark secrets about each other and the true intentions behind their research. With their lives on the line and the fate of humanity hanging in the balance, the team must confront their own personal demons and confront the question: what is the true cost of progress?</em></p><p>Wow Dr.Fox seems pretty impressive. To further this claim, <a href="https://www.andrewng.org/">Andrew Ng</a>, a globally recognized leader in AI says a “zero shot work flow” <em>(A “zero shot workflow” refers to the process where a model is asked to perform a task without any prior specific training or examples on that task. In simpler terms, the model uses only its pre-trained knowledge and understanding to generate a response based on the single prompt it receives. This approach is called “zero shot” because the model gets zero examples or specific guidance about the task beforehand.) </em>with GPT-3.5 got a human evaluation bench mark of 48% but when wrapped in an “Agentic” work flow <em>(An “Agentic workflow” involves a more interactive and iterative approach where the model’s output from previous interactions is used to refine and improve subsequent prompts or tasks. This term highlights the model’s role as an active agent that contributes to an ongoing process. In practice, this means that after receiving an initial response from the model, you refine your prompt based on the information provided, and send it back to the model.)</em> the evaluation percentage jumped to 95%. So What Ng is saying here is basically GPT-3.5 performs better with a workflow applied to it than GPT-4 with a zero shot. To me, this is extremely powerful.</p><h4>Testing the Model</h4><p>Crafting the perfect prompt does not only lie within using the correct text on first try. Testing your prompt against multiple models is a great way to see what model works best for you in a specific use case. In <a href="https://formulaic.app/">Formulaic.app</a> you can run the same prompt chain against many different models. This is a great way to craft your prompt against a model that supports the direction you are trying to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41Jfp9Yy_3yGPBBKx-GkYw.png" /></figure><h4>Continuing the Chat</h4><p>A unique feature about this interface (coming out soon) is the ability to continue chatting with the result. If you follow all the prompting rules, like being specific about your request or avoiding impreciseness, there is still a lot to be discovered when picking at the result with further questioning. I found this helpful when crafting additional prompts to add to the prompt chain or just to get some quick feed back on if a specific model is appropriate for me. It’s also helpful in getting a better idea on how models respond to specific language thereby improving your overall prompting ability.</p><p>There are a lot of resources on how to create prompts but at the end of the day this landscape is new and creativity is really our only limiting factor. I’d suggest signing up for <a href="https://formulaic.app/">Formulaic.app</a> with a free account and see what you can create.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01249e5f05ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing the Power of Web Workers with Next.js]]></title>
            <link>https://medium.com/@ngrato/harnessing-the-power-of-web-workers-with-next-js-350901a99a10?source=rss-f3fc76aef1e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/350901a99a10</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Nick Grato]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 16:31:33 GMT</pubDate>
            <atom:updated>2024-06-14T21:31:22.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EVC2sijFa7_AvWKEhF_Mw.jpeg" /></figure><p>Delivering real-time data efficiently is crucial for maintaining the responsiveness of web applications. Though this post is not about finance, data like cryptocurrency prices can fluctuate rapidly and therefor is a great use case for a Web Worker. Traditional methods of handling this data can bog down the <a href="https://developer.mozilla.org/en-US/docs/Glossary/Thread">main thread</a>, leading to sluggish user interfaces. However, by leveraging the power of Web Workers, we can offload this data handling to a separate thread, keeping our UI swift and responsive. In this post, I’ll walk you through how I used Web Workers in a Next.js application to manage real-time cryptocurrency data. Here’s a screen shot of the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfmKsZs_wsEfEXu6kNLXew.png" /><figcaption>Crypto Currency UI</figcaption></figure><h3>What are Web Worker</h3><p>In short, Web Workers provide a way to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. Plus, they can send messages to the main JavaScript thread, ensuring your application remains responsive. <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Read more</a></p><h3>Setting the Stage: Next.js and Web Workers</h3><p>Next.js is a React framework that enables developers to build server-side rendering and static web applications. I have a love hate relationship with Next.js that I wont go much into here but since I use it at work and it’s so popular I wanted to figure out how to use Web Workers with Next.js specifically. Some hurdles I wanted to overcome</p><ul><li>Use Typescript</li><li>Have the Web Worker file path available to any component</li><li>Not pollute my current <em>tsconfig.json</em> file or dumping all my files into the public directory</li></ul><h3>Build Phase</h3><p>Before getting into the actual Web Worker let’s do the boring stuff first. To make the Web Worker available at run time we need to store it in the <em>/public</em> directory. A quick note on the public directory — it’s intended for static files such as images, fonts, scripts, and HTML files that need to be accessed directly via the browser. Anything placed in this directory is served by Next.js as a static resource. This setup does bring with it a few security considerations. Avoid sensitive user data, use appropriate security headers, and don’t store any API keys in these files.</p><h3>Create New tsconfig.json</h3><p>I first extend <em>tsconfig.json</em> by creating a new file named <em>tsconfig.worker.json</em> to compile specific Web Worker files into the <em>/public </em>directory. If I put this same JSON on the main config I believe the <em>compilerOption -&gt; outDir</em> would put everything into the <em>/public</em> directory.</p><pre>{<br>  &quot;extends&quot;: &quot;./tsconfig.json&quot;,<br>  &quot;compilerOptions&quot;: {<br>    &quot;outDir&quot;: &quot;./public/workers&quot;,<br>    &quot;module&quot;: &quot;ES6&quot;,<br>    &quot;noEmit&quot;: false<br>  },<br>  &quot;include&quot;: [<br>    &quot;workers/**/*.ts&quot;<br>  ]<br>}</pre><p>This will now take any files in the <em>/workers</em> and compile it to JavaScript and put it in the <em>/public/workers</em> directory for us to access in any of our components.</p><h3>Update Package.json</h3><p>In your <em>package.json</em> file you will need to update the scripts so that the worker files will build on save. This is the way I did it, I’m sure there are better solutions here. I first added a script command for just building -</p><pre>&quot;build:workers&quot;: &quot;tsc -p tsconfig.worker.json&quot;,</pre><p>And then I added a command to watch my worker folder for changes and to build after saving. I ran this command in parallel with the dev command. But you could update you dev command to do this all at once.</p><pre>&quot;watch:workers&quot;: &quot;tsc -p tsconfig.worker.json --watch&quot;,<br>&quot;dev&quot;: &quot;next dev -H 127.0.0.1 -p 3111&quot;,</pre><h3>The Web Worker</h3><p>Web workers aren’t terribly complex, at the end of the day they really only have 4 methods and 2 properties. The methods can be use to communicate into and out of the Web Worker and the properties to listen to these event.</p><h4>Methods</h4><ul><li><strong>postMessage()</strong>: Sends a message to the worker’s inner scope. This can be any value or JavaScript object but not functions or error objects.</li></ul><pre>worker.postMessage(data);</pre><ul><li><strong>terminate()</strong>:<br> Immediately terminates the worker. This stops all operations in the worker’s scope, closes all network connections, and frees up any resources. After calling `terminate()`, the worker cannot be restarted.</li></ul><pre>worker.terminate();</pre><ul><li><strong>addEventListener()</strong>:<br> An alternative to setting properties directly on the worker for handling events like `message` and `error`.</li></ul><pre>worker.addEventListener(&#39;message&#39;, handlerFunction);</pre><ul><li><strong>removeEventListener()</strong>:<br>Removes an event listener previously registered with addEventListener().</li></ul><pre>worker.removeEventListener(&#39;message&#39;, handlerFunction);</pre><h4>Properties</h4><ul><li><strong>onmessage</strong>: An event handler that is called when the worker receives a message from the main thread using `postMessage()`.</li></ul><pre>worker.onmessage = function(event) { <br>  console.log(event.data); <br>};</pre><ul><li><strong>onerror</strong>: Description: An event handler that is called when an error occurs in the worker. This event handler can receive an `ErrorEvent` object containing information about the error.</li></ul><pre>worker.onerror = function(event) { console.error(event.message); };</pre><p>By creating your own message types for example ‘init’ or ‘data’ when using the <em>postMessage</em> method it can instill organization and flexibility. For example I have these Typescript types in this project to outline the type of message to funnel the payload into a specific algorithm in the Web Worker. I just used the work ‘type’ a lot there how about I just show an example.</p><p><strong>types.ts</strong></p><pre>export type WorkerMessageT&lt;T&gt; = {<br>  type: &#39;init&#39; | &#39;data&#39; | &#39;error&#39; | &#39;stop&#39;<br>  payload?: {<br>    id?: string<br>    data: T<br>  }<br>}<br><br>export type CryptoWorkConfigT = {<br>  assets: string // bitcoin,ethereum,monero,litecoin<br>}</pre><p>Another way you could accomplish this is to leverage the <em>addEventListener</em>().</p><p><strong>crypto.ts</strong></p><pre>import { WorkerMessageT, CryptoWorkConfigT } from &#39;../types&#39;<br><br>// Define pricesWs at the top-level scope of the worker<br>let pricesWs: WebSocket | null = null<br><br>self.onmessage = (e) =&gt; {<br>  const BASE_URL = &#39;wss://ws.coincap.io/prices&#39;<br>  switch (e.data.type) {<br>    case &#39;init&#39;:<br>      const message: WorkerMessageT&lt;CryptoWorkConfigT&gt; = e.data<br><br>      // Initialize the WebSocket connection<br>      pricesWs = new WebSocket(<br>        `${BASE_URL}?assets=${message.payload?.data.assets}`,<br>      )<br><br>      const initSubscription = () =&gt; {<br>        pricesWs?.addEventListener(&#39;message&#39;, function (event) {<br>          self.postMessage(JSON.parse(event.data))<br>        })<br>      }<br><br>      initSubscription()<br><br>      break<br><br>    case &#39;stop&#39;:<br>      // Safely close the WebSocket if it&#39;s open<br>      if (pricesWs) {<br>        console.log(&#39;Closing WebSocket connection...&#39;, pricesWs)<br>        pricesWs.close()<br>        pricesWs = null // Clear the reference after closing<br>      }<br>      break<br><br>    case &#39;error&#39;:<br>      // Handle error, possibly closing WebSocket<br>      if (pricesWs) {<br>        pricesWs.close()<br>        pricesWs = null // Ensure clean up on error<br>      }<br>      // Implement additional error handling logic here<br>      break<br><br>    default:<br>      // Handle any cases that are not explicitly mentioned<br>      console.error(&#39;Unhandled message type:&#39;, e.data.type)<br>  }<br>}</pre><p>First I’m importing a few Types, and I initialize a Web Socket variable that I will be using to communicate with the Coincap API. Then I have the first Web Worker method <em>self.onmessage</em>. You can see that the message type is immediately useful by bifurcating the event to the correct algorithm. In the ‘init’ case I gather the incoming message data and subscribe to the Coincap Web Socket. In the Web Socket event handler I use the <em>postmessage()</em> method to broadcast the data. That’s it! Let’s move onto the UI where I communicate with the Web Worker.</p><p><strong>page.ts</strong></p><pre>&#39;use client&#39;<br><br>import { useEffect, useRef, useState } from &#39;react&#39;<br>import { Button } from &#39;@mozilla/lilypad-ui&#39;<br>import styles from &#39;./page.module.scss&#39;<br>import { CryptoWorkConfigT, WorkerMessageT } from &#39;workers/types&#39;<br>import Card from &#39;@Shared/Card/Card&#39;<br><br>type CryptoDataT = {<br>  bitcoin: string<br>  ethereum: string<br>  monero: string<br>  litecoin: string<br>}<br><br>const page = () =&gt; {<br>  const workerRef = useRef&lt;Worker&gt;()<br>  const initPrice = &#39;waiting for data...&#39;<br>  const [status, setStatus] = useState&lt;string&gt;(&#39;Stopped&#39;)<br>  const [prices, setPrices] = useState&lt;CryptoDataT&gt;({<br>    bitcoin: &#39;&#39;,<br>    ethereum: &#39;&#39;,<br>    monero: &#39;&#39;,<br>    litecoin: &#39;&#39;,<br>  })<br><br>  useEffect(() =&gt; {<br>    workerRef.current = new Worker(&#39;/workers/crypto/crypto.js&#39;, {<br>      type: &#39;module&#39;,<br>    })<br>    workerRef.current.onmessage = (event) =&gt; {<br>      setPrices((prev) =&gt; {<br>        const newState = { ...prev, ...event.data }<br>        return newState<br>      })<br>    }<br>    workerRef.current.onerror = (error) =&gt; {<br>      console.error(&#39;Worker error:&#39;, error)<br>    }<br>    return () =&gt; {<br>      if (workerRef.current) {<br>        workerRef.current.terminate()<br>      }<br>    }<br>  }, [])<br><br>  const startWorker = () =&gt; {<br>    setStatus(&#39;Running&#39;)<br><br>    const workerMessage: WorkerMessageT&lt;CryptoWorkConfigT&gt; = {<br>      type: &#39;init&#39;,<br>      payload: {<br>        data: {<br>          assets: &#39;bitcoin,ethereum,monero,litecoin&#39;,<br>        },<br>      },<br>    }<br>    if (workerRef.current) {<br>      workerRef.current.postMessage(workerMessage)<br>    }<br>  }<br><br>  const stopWorker = () =&gt; {<br>    setStatus(&#39;Stopped&#39;)<br>    const workerMessage: WorkerMessageT&lt;CryptoWorkConfigT&gt; = {<br>      type: &#39;stop&#39;,<br>    }<br>    if (workerRef.current) {<br>      workerRef.current.postMessage(workerMessage)<br>    }<br>  }<br><br>  const terminateWorker = () =&gt; {<br>    setStatus(&#39;Terminated&#39;)<br>    const workerMessage: WorkerMessageT&lt;CryptoWorkConfigT&gt; = {<br>      type: &#39;stop&#39;,<br>    }<br>    if (workerRef.current) {<br>      workerRef.current.postMessage(workerMessage)<br>      workerRef.current.terminate()<br>    }<br>  }<br><br>  return (<br>    &lt;section className={styles.page}&gt;<br>      &lt;Card size=&quot;large&quot; classProp={styles.card}&gt;<br>        &lt;div className=&quot;mb-40 gap-12&quot;&gt;<br>          &lt;Button onClick={startWorker} text=&quot;Start stream&quot; /&gt;<br>          &lt;Button<br>            onClick={stopWorker}<br>            text=&quot;Stop stream&quot;<br>            category=&quot;primary_outline&quot;<br>          /&gt;<br>          &lt;Button<br>            icon=&quot;trash&quot;<br>            onClick={terminateWorker}<br>            text=&quot;Terminate Worker&quot;<br>            category=&quot;primary_clear&quot;<br>          /&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;h2 className=&quot;heading-md mb-12&quot;&gt;Stream data: {status}&lt;/h2&gt;<br>          &lt;p className=&quot;mb-40 body-sm&quot;&gt;<br>            This page uses a Web Worker to stream cryptocurrency prices from<br>            CoinCap.io. The worker is started when you click the &quot;Start stream&quot;<br>            button and stopped when you click the &quot;End stream&quot; button.<br>          &lt;/p&gt;<br>          &lt;div className=&quot;gap-12 flex-column&quot;&gt;<br>            {Object.keys(prices).map((key) =&gt; {<br>              const price = prices[key as keyof CryptoDataT]<br>              return (<br>                &lt;div key={key}&gt;<br>                  &lt;span className=&quot;mr-12 capitalize&quot;&gt;{key}:&lt;/span&gt;<br>                  &lt;span className={`${!price &amp;&amp; &#39;opacity-20&#39;}`}&gt;<br>                    {price ? &#39;$&#39; + price : initPrice}<br>                  &lt;/span&gt;<br>                &lt;/div&gt;<br>              )<br>            })}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/Card&gt;<br>    &lt;/section&gt;<br>  )<br>}<br><br>export default page</pre><p>To kick things off, in the <em>useEffect</em> I created the Web Worker and subscribed to it’s events (The file path should be directed to the file that will be compiled in your <em>/public</em> directory). You can see that in the <em>onmessage</em> event I am updating the component state to reflect the most current crypto prices. In the JSX I created a button to turn the Web Worker on but you could just as easily begin the process on page load in the <em>useEffect</em>.</p><p>Additional functionality is in the click handlers “startWorker”, “stopWorker”, and “terminateWorker”. These handlers are not mandatory but I felt like this was a nice way to organize the functionality. Their names are pretty obvious what they do, but if you take a second look at them you can see how the “type” of message that’s being posted can make the Web Worker communication much more predictable.</p><h3>Conclusion</h3><p>Web Workers can be used for a lot more interesting things that this example but I hope this introduction was helpful to get a conceptual grasp on them. Or if like me, you struggled usinged Web Workers with Next.js, that this would aleast point you in the right direction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=350901a99a10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Generics in React Component Props for Flexible UI Components]]></title>
            <link>https://medium.com/@ngrato/leveraging-generics-in-react-component-props-for-flexible-ui-components-8589661993da?source=rss-f3fc76aef1e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8589661993da</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Nick Grato]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 00:03:11 GMT</pubDate>
            <atom:updated>2024-03-22T00:08:26.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gCu_oRq1mk81iabcGscp4Q.png" /><figcaption>keyboard</figcaption></figure><p>Using Generics can be intimidating. I found when I initially learned about Generics I had a hard time understanding where I could use this feature. It also seemed that every example I looked up ( this was a long time ago while working in C# ) that every example was overly complex. At the end of the day, it’s a way to pass a parameter to a type to have a dynamic attribute in said type. The syntax is TypeT&lt;T&gt;, where TypeT is the type name and T is a conventional way to represent the parameter. For example:</p><pre>type ButtonTogglePropsT&lt;T&gt; = {<br>  onClick?: (value: T) =&gt; void;<br>};</pre><p>Before we look at anymore code let’s go over a quick example that you might have came across. When returning data from a fetch we receive a Promise, the return value from the API could be anything, or you could say generic? That’s why the Promise return type is in fact a Generic. This gives you the ability to pass the type of the returned data “Promise&lt;T&gt; — Promise&lt;MyDataResponseT&gt;”.</p><p>With a small example out of the way, how might using Generics in a component’s prop be useful? Here’s the scenario I ran across. I had to create a button toggle component that fulfilled the following criteria:<br>- Have a group of buttons a user could click that share a common state (IE On click the button would need to be set to active and all other deactivated)<br>- The component would need to emit the value of the clicked button on event click.<br>- The value emitted would need to be a specific type (BillingPeriodT) but that type needs to be interchangeable.</p><p>Here the UI :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*tq6VVsz2m_4XeHFH77nxYg.png" /><figcaption>button toggle UI</figcaption></figure><h4>Pull out the Generics</h4><p>This example makes it pretty clear, we need to be able to dynamically change the types that this button group uses. If not, this component could only be used in one place, and thereby not fulfilling all the specs.</p><p>Implementing a generic on a React component is simple. I prefer to use arrow function when I create components so this example uses them. You do not have to use arrow functions for this to work.</p><pre>type ButtonTogglePropsT&lt;T&gt; = {<br>  options: ButtonToggleOptions&lt;T&gt;[];<br>  onClick?: (value: T) =&gt; void;<br>  className?: string;<br>};<br>const ButtonToggle = &lt;T,&gt;({<br>  options,<br>  onClick,<br>  className = &#39;&#39;,<br>}: ButtonTogglePropsT&lt;T&gt;) =&gt; {<br>  {<br>  }<br>  // component code here<br>};</pre><p>Again, “T” represents the generic, and that is where the generic value will be replaced. You can see that it is used in a couple places. At the components name ButtonToggle for the entry point and then again passed to the props type. We are then applying the generic type to what value is being sent from the click handler. That value should now be able to match whatever type we have in the parent state.</p><h4><strong>Implementation</strong></h4><pre>type BillingPeriodT = &#39;monthly&#39; | &#39;yearly&#39;;<br>const [billingPeriod, setBillingPeriod] = useState&lt;BillingPeriodT&gt;(&#39;monthly&#39;);<br>const BILLING_OPTIONS = [<br>  { label: &#39;Monthly&#39;, value: &#39;monthly&#39; },<br>  { label: &#39;Annual&#39;, value: &#39;yearly&#39; },<br>];<br><br>&lt;ButtonToggle&lt;BillingPeriodT&gt;<br>  options={BILLING_OPTIONS}<br>  onClick={(value: BillingPeriodT) =&gt; {<br>    setBillingPeriod(value);<br>  }}<br>/&gt;;</pre><p>I added the type and parent state to give you a full picture. Looking back on the specs I needed to accomplish, this component is now able to set any type of data to the button values in the ButtonToggle. For example I could create new type that has more complexity than a string union.</p><pre>type UserT = {<br>  id: UUID;<br>  name: string;<br>  role: &#39;user&#39; | &#39;admin&#39;;<br>};<br>const [currentUser, setCurrentUser] = useState&lt;UserT&gt;();<br>const USER_OPTIONS = [<br>  {<br>    label: &#39;Judy&#39;,<br>    value: {<br>      id: &#39;32343243243&#39;,<br>      name: &#39;Judy&#39;,<br>      role: &#39;user&#39;,<br>    },<br>  },<br>  {<br>    label: &#39;Jon&#39;,<br>    value: {<br>      id: &#39;32343243243&#39;,<br>      name: &#39;Jon&#39;,<br>      role: &#39;admin&#39;,<br>    },<br>  },<br>];<br>&lt;ButtonToggle&lt;UserT&gt;<br>  options={USER_OPTIONS}<br>  onClick={(user: UserT) =&gt; {<br>    setCurrentUser(user);<br>  }}<br>/&gt;;</pre><p>Even though the type is a bit more complex you can see it is just as easy to use this type in the component and a string union.</p><p>The power of generics offer a pathway to creating highly reusable and adaptable components in React. By embracing generics, we unlock a higher level of flexibility and type safety in our components.</p><h4><strong>Full Component</strong></h4><pre>import { Button } from &#39;@mozilla/lilypad-ui&#39;;<br>import { useState } from &#39;react&#39;;<br>import styles from &#39;./ButtonToggle.module.scss&#39;;<br><br>export type ButtonToggleOptions&lt;T&gt; = {<br>  label: string;<br>  value: T;<br>};<br><br>type ButtonTogglePropsT&lt;T&gt; = {<br>  options: ButtonToggleOptions&lt;T&gt;[];<br>  onClick?: (value: T) =&gt; void;<br>  className?: string;<br>};<br><br>const ButtonToggle = &lt;T,&gt;({<br>  options,<br>  onClick,<br>  className = &#39;&#39;,<br>}: ButtonTogglePropsT&lt;T&gt;) =&gt; {<br>  const [currentValue, setCurrentValue] = useState(options[0].value);<br><br>  /**<br>   * Handle Button Click<br>   * @param value<br>   */<br>  const handleButtonClick = (value: T) =&gt; {<br>    setCurrentValue(value);<br>    onClick &amp;&amp; onClick(value);<br>  };<br><br>  return (<br>    &lt;div className={`${className} ${styles.wrapper}`}&gt;<br>      {options.map(({ value, label }) =&gt; (<br>        &lt;Button<br>          label={label}<br>          text={label}<br>          key={label}<br>          onClick={() =&gt; {<br>            handleButtonClick(value);<br>          }}<br>          category={value === currentValue ? &#39;primary_solid&#39; : &#39;primary_clear&#39;}<br>        /&gt;<br>      ))}<br><br>      <br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ButtonToggle;</pre><pre>.wrapper {<br>  display: inline-block;<br>  background-color: $color-neutral-0;<br>  border-radius: 35px;<br>  padding: 6px;<br>  white-space: nowrap;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8589661993da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical React Patterns : Dynamic Styling]]></title>
            <link>https://medium.com/@ngrato/practical-react-patterns-dynamic-styling-2e4b700dbdac?source=rss-f3fc76aef1e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e4b700dbdac</guid>
            <category><![CDATA[scss]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Nick Grato]]></dc:creator>
            <pubDate>Wed, 09 Nov 2022 23:29:38 GMT</pubDate>
            <atom:updated>2022-11-09T23:30:22.001Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Space man" src="https://cdn-images-1.medium.com/max/1024/1*qYuiCvtLQSwS2-SKRV-hHA.jpeg" /></figure><h3>Practical React Patterns : Dynamic Styling</h3><p>I came across this pattern working with my team at Mozilla, so I can’t take full credit. However, I found this method of working with components too simple and elegant not to share. Long story short this is a great way to manage a component that takes a large number of styling props. This pattern will help you map prop parameters to your SCSS files in a clean, scalable way</p><p>Before getting into the weeds, the ideal setup for this pattern is TypeScript (we will be using enums) and React CSS Modules ( using enums to pinpoint values on the styles object ).</p><p>If you are impatient like me you can scroll down to the code, it is simple to understand, if you are interested in the what and why, stick around.</p><h3>The Problem</h3><p>I was tasked with creating a React component library, of course, we need to have buttons in the library so I started there. I quickly realized just a simple button that needed to cover all aspects of what the button “could” be was not so simple. We only have a “primary” and a “secondary” button style but both primary and secondary styles encapsulate a “solid”, “outline” and “clear” type. Not to mention each has :focus, :disabled, :hover styles. Oh yea and we have a light and dark mode. Oh and also, the buttons will have a “small”, “medium” and “large” option. That’s a lot.</p><p>In addition to stuffing all of this functionality into one component, I also wanted to make the implementation of the button, from the DX side, extremely easy . A component library is only as good as how easy it is to use.</p><h3>The implementation</h3><p>After writing a lot of bad code, I went back to the drawing board. One thing I felt was right about my bad code was I had some pretty nice enums that outlined all the button names. I also had some pretty clean SCSS going on. It hit me that there was almost a perfect one to one pattern with my enums and my SCSS. With a little tweaking I could make it a perfect one and use the JSX as just a middle-man for my enum and SCSS to communicate.</p><p>I have not been a huge fan of how React handles CSS, but having the styles imported as an object did open up doors for more possibilities. In this case I had the styles I wanted and the enums established, but how could I connect these to worlds? Good ole bracket notation!</p><h3>The Code</h3><p>First we have the button categories and sizes declared in enums.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39b54a8503d191b734e12ab3151e59dd/href">https://medium.com/media/39b54a8503d191b734e12ab3151e59dd/href</a></iframe><p>Here is an example of the primary button “solid” and the size styles breakdown in the SCSS. Look to the<strong> ButtonCategoriesE </strong>enum to get an idea of what all the other CSS classes would look like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7503b2e0c0e05d02dcbd2d88a313b88/href">https://medium.com/media/c7503b2e0c0e05d02dcbd2d88a313b88/href</a></iframe><p>The Button component will have, among others, the category prop and the size prop. I like to set defaults to the most likely scenario, in this case that would be a “solid/medium” button.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb8fd1119250160b7f5b2e1985b77641/href">https://medium.com/media/eb8fd1119250160b7f5b2e1985b77641/href</a></iframe><p>Using the Button component is very powerful now with just two styling pops. This is an example of an “outlined/large” button.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc64b7452ad791779f0b26848f5ee915/href">https://medium.com/media/cc64b7452ad791779f0b26848f5ee915/href</a></iframe><p>Hopefully you found this pattern helpful. Leave a comment if you thought this was great or, on the other hand, have some suggestions to make it better!</p><p>Stay Learning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e4b700dbdac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shopify Collection Filtering]]></title>
            <link>https://medium.com/@ngrato/shopify-collection-filtering-2882737227fb?source=rss-f3fc76aef1e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2882737227fb</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[shopify-development]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nick Grato]]></dc:creator>
            <pubDate>Sun, 06 Feb 2022 18:08:12 GMT</pubDate>
            <atom:updated>2022-02-06T18:38:35.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*vNUJZOiTnLWaoSBhm30RNw.jpeg" /></figure><p>One of the most confusing parts of creating an Shopify store is: filtering and sorting the products, in a fast scalable way. Today I’d like to show you how I filter my products in Shopify. Shopify’s domain language for a group of products is called a “<em>collection</em>”. I’ll refer to this feature we are working on as a collection for the rest of the post.</p><p>Note: Shopify has a built in way to query products using url params and tags. If you have a very simple collection and only have a few small filters this could be a better approach. If you need more control over the filters and don’t want to refetch products or possibly you have a more headless approach my filter might be a better option. For a great explanation of Shopify tag filtering see <a href="https://christopherdodd.com/shopify-collection-filtering/">christopherdodd</a>.</p><p>Back to business. Say you have a collection of the timeless product, the T-shirt, your business requirements are to filter these shirts by color. So, you write a little filter like this when the user clicks a red swatch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/347afc2fa9419c588b4c63afd705a68a/href">https://medium.com/media/347afc2fa9419c588b4c63afd705a68a/href</a></iframe><p>A couple days later your project manager says “shouldn’t we filter by size as well” so you think to yourself ok so now I need to make a filter so that I can find a “red” / “small” T-shirt. You assume the logical approach and filter products down having to be red AND small. You are proud of your work but before the end of the day you get pulled aside by your project manager and she says you need to add yet another filter. “We need to filter by material now too, and while you are at it, let’s filter by different color combinations”. This filter is beginning to get complex and you are also thinking now how many more filters are they going to add. Can’t we find a way to add filters more easily?</p><p>I saw this filter design pattern a while back online somewhere. I’d credit the author if I could remember where, but until then, I’ll just give a shout out to the mystery man.</p><h3>Create the Mega Filter</h3><p>The <em>MegaFilter</em> class accepts the products array and a specification parameter. I will shed more light on the specification parameter in the coming steps. But basically this little bit of code orchestrates the entire filter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a718c3dde1f584557fa9b527ac097249/href">https://medium.com/media/a718c3dde1f584557fa9b527ac097249/href</a></iframe><h3>Create the “Or” Specification</h3><p>The <em>OrSpecification</em> class accepts custom specifications we will create in the next step. This class loops through all of the specifications it has been given and checks if at least one of the specifications are met on a product. For example if we made a specification that the shirt needed to be blue and another one that needed it to be red and fed both of those specifications to the <em>OrSpecification</em>, then it would filter products that are blue or red.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4c8c3f2ec5ac3f8218d5222fb0a1855/href">https://medium.com/media/d4c8c3f2ec5ac3f8218d5222fb0a1855/href</a></iframe><h3>Create the “And” Specification</h3><p>The <em>AndSpecification</em> class also accepts custom specifications. It works exactly like the <em>OrSpecification</em> but instead of checking if only one specification was met it makes sure all specifications are met on the product to pass.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05b808e7fd601b7ea13bb78b327029d2/href">https://medium.com/media/05b808e7fd601b7ea13bb78b327029d2/href</a></iframe><h3>Create the Custom Specifications</h3><p>Now to the fun part! This is where we will start writing actual filters. These are the specifications that we will pass into the “and” and “or” specification classes. Each of these classes will accept different parameters depending on what attribute you want to compare the product data to. Here is an example of a color filter that just accepts a string for the color.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ba44bd5e6fcace4147d6d828f47e129/href">https://medium.com/media/1ba44bd5e6fcace4147d6d828f47e129/href</a></iframe><h3>Put It Together</h3><p>Pretty easy right? So let’s put it all together. Using the orchestrating classes in the code below ( I’m going to put this all on one file for ease of use. I’m also going to throw in a price specification for another example.) we can apply our custom specifications to our mega filter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be29802e6ef6683a428f3ba40fb4257e/href">https://medium.com/media/be29802e6ef6683a428f3ba40fb4257e/href</a></iframe><p>Hopefully this filter pattern can be of use to you. I’m sure you have guessed it by now but this pattern could be used to filter really anything else you wanted. I used this pattern just the other day to filter stores on a map for a store locator ( I’ll post more on that later).</p><p>That’s all for now, <a href="https://gratocodes.com/contact">send me a message</a> it you have any questions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2882737227fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>