<?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 Sachin Chaurasiya on Medium]]></title>
        <description><![CDATA[Stories by Sachin Chaurasiya on Medium]]></description>
        <link>https://medium.com/@sachin-chaurasiya?source=rss-74fad1116d0a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*u3achYKpQMz9AS75u0rrOA.png</url>
            <title>Stories by Sachin Chaurasiya on Medium</title>
            <link>https://medium.com/@sachin-chaurasiya?source=rss-74fad1116d0a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:12:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sachin-chaurasiya/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 #1 Skill Most Developers Miss When Using AI Coding Agents]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://sachin-chaurasiya.medium.com/the-1-skill-most-developers-miss-when-using-ai-coding-agents-42c70ba73aa9?source=rss-74fad1116d0a------2"><img src="https://cdn-images-1.medium.com/max/864/1*CU9wDgfMZkZtbjgU6Lqqcw.png" width="864"></a></p><p class="medium-feed-snippet">The debate over AI coding agents is missing the most important factor. It&#x2019;s not about prompt engineering, it&#x2019;s about understanding the&#x2026;</p><p class="medium-feed-link"><a href="https://sachin-chaurasiya.medium.com/the-1-skill-most-developers-miss-when-using-ai-coding-agents-42c70ba73aa9?source=rss-74fad1116d0a------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://sachin-chaurasiya.medium.com/the-1-skill-most-developers-miss-when-using-ai-coding-agents-42c70ba73aa9?source=rss-74fad1116d0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/42c70ba73aa9</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Sachin Chaurasiya]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 17:45:11 GMT</pubDate>
            <atom:updated>2026-01-03T17:45:11.276Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to Build Production-Grade Agentic AI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://ai.plainenglish.io/how-to-build-production-grade-agentic-ai-6c388867dbd5?source=rss-74fad1116d0a------2"><img src="https://cdn-images-1.medium.com/max/1000/0*z3jMdQ-Fu2262G_x.png" width="1000"></a></p><p class="medium-feed-snippet">Agentic AI is everywhere right now.</p><p class="medium-feed-link"><a href="https://ai.plainenglish.io/how-to-build-production-grade-agentic-ai-6c388867dbd5?source=rss-74fad1116d0a------2">Continue reading on Artificial Intelligence in Plain English »</a></p></div>]]></description>
            <link>https://ai.plainenglish.io/how-to-build-production-grade-agentic-ai-6c388867dbd5?source=rss-74fad1116d0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c388867dbd5</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Sachin Chaurasiya]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 13:41:42 GMT</pubDate>
            <atom:updated>2025-12-25T11:29:17.941Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How web worker works with a practical example]]></title>
            <link>https://blog.devgenius.io/how-web-worker-works-with-a-practical-example-16c85b308df0?source=rss-74fad1116d0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/16c85b308df0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Sachin Chaurasiya]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 12:50:38 GMT</pubDate>
            <atom:updated>2025-03-06T16:58:02.038Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*bE22K2HmLUJEt5BR.png" /></figure><p>Ever noticed a webpage freezing during a heavy task? This happens because JavaScript runs on a single thread by default, causing a bad user experience. Users can’t interact and have to wait until the task finishes. This problem can be solved using web workers. In this article, we will discuss what web workers are, why they are useful, and how to use them with a practical example by building an image compression application. Exciting, right? Let’s get started.</p><h3>What are Web Workers?</h3><p>Web Workers let JavaScript run tasks in the background <strong>without blocking the main thread</strong>, which keeps your UI smooth and responsive. You can create them using the Web Workers API, which takes two parameters: url and options. Here is a simple example of creating a web worker.</p><pre>const worker = new Worker(&#39;./worker.js&#39;, { type: &#39;module&#39; });</pre><h3>Why use Web Workers?</h3><p>As mentioned earlier, web workers run tasks in the background. Here are a few reasons to use them</p><ul><li>Prevents page lag during heavy computations</li><li>Handles large data processing efficiently</li><li>Improves performance for complex web applications</li></ul><h3>How do they work?</h3><ol><li>The main thread <strong>creates a worker</strong> and gives it a task</li><li>The worker <strong>handles the task in the background</strong></li><li>When finished, it <strong>sends the result back</strong> to the main thread</li></ol><p>Alright, now we know what a web worker is, why to use them, and how they work. But that’s not enough, right? So let’s build the image compression application and see how to use web workers in practice.</p><h3>Project setup</h3><p>Create a Next.js project with TypeScript and Tailwind CSS</p><pre>npx create-next-app@latest --typescript web-worker-with-example <br><br>cd web-worker-with-example</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*RFPf-BKw9_9hN4sZ.png" /></figure><p>To compress images in the browser, we will use the @jsquash/web npm library to encode and decode WebP images. This library is powered by WebAssembly, so let&#39;s install it.</p><pre>npm install @jsquash/webp</pre><p>Great, our project setup is complete. In the next section, we will create a worker script to manage image compression.</p><h3>Creating worker script</h3><p>A worker script is a JavaScript or TypeScript file that contains the code to handle worker message events.</p><p>Create an imageCompressionWorker.ts file inside the src/worker folder and add the following code.</p><pre>/// &lt;reference lib=&quot;webworker&quot; /&gt;<br><br>const ctx = self as DedicatedWorkerGlobalScope;<br><br>import { decode, encode } from &#39;@jsquash/webp&#39;;<br><br>ctx.onmessage = async (<br>  event: MessageEvent&lt;{<br>    id: number;<br>    imageFile: File;<br>    options: { quality: number };<br>  }&gt;<br>) =&gt; {<br>  // make sure the wasm is loaded<br>  await import(&#39;@jsquash/webp&#39;);<br><br>  const { imageFile, options, id } = event.data;<br>  const fileBuffer = await imageFile.arrayBuffer();<br>  try {<br>    const imageData = await decode(fileBuffer);<br>    const compressedBuffer = await encode(imageData, options);<br>    const compressedBlob = new Blob([compressedBuffer], {<br>      type: imageFile.type,<br>    });<br>    ctx.postMessage({ id, blob: compressedBlob });<br>  } catch (error: unknown) {<br>    const message = error instanceof Error ? error.message : &#39;Unknown error&#39;;<br>    ctx.postMessage({ id, error: message });<br>  }<br>};<br><br>export {};</pre><p>Here, we import the encode and decode methods from the @jsquash/webp library and use the worker global scope, self, to listen for messages from the main thread.</p><p>When a message arrives, we get the image file and options, then compress the image by first decoding and then encoding it with the quality option. Finally, we use postMessage to send the compressed image blob back to the main thread. If there&#39;s an error, we handle it and send the error message back using postMessage.</p><p>The worker script is ready. In the next section, we will build the Imagelist component, update the styles, update the page, and use the worker script to handle the compression.</p><h3>Using the web worker</h3><p>Before we start, let’s update the global.css file with the following content and remove the default styling.</p><pre>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><p>Create a ImageList.tsx in the src/components folder and add the following code.</p><pre>/* eslint-disable @next/next/no-img-element */<br>import React from &#39;react&#39;;<br><br>export type ImgData = {<br>  id: number;<br>  file: File;<br>  status: &#39;compressing&#39; | &#39;done&#39; | &#39;error&#39;;<br>  originalUrl: string;<br>  compressedUrl?: string;<br>  error?: string;<br>  compressedSize?: number;<br>};<br><br>interface ImageListProps {<br>  images: ImgData[];<br>}<br><br>const formatBytes = (bytes: number): string =&gt; {<br>  if (bytes === 0) return &#39;0 Bytes&#39;;<br>  const k = 1024;<br>  const dm = 2;<br>  const sizes = [&#39;Bytes&#39;, &#39;KB&#39;, &#39;MB&#39;, &#39;GB&#39;, &#39;TB&#39;];<br>  const i = Math.floor(Math.log(bytes) / Math.log(k));<br>  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + &#39; &#39; + sizes[i];<br>};<br><br>const ImageList: React.FC&lt;ImageListProps&gt; = ({ images }) =&gt; {<br>  return (<br>    &lt;div className=&quot;mt-4&quot;&gt;<br>      &lt;h2 className=&quot;text-xl font-semibold mb-2&quot;&gt;Image List&lt;/h2&gt;<br>      &lt;div className=&quot;space-y-4&quot;&gt;<br>        {images.map((img) =&gt; (<br>          &lt;div<br>            key={img.id}<br>            className=&quot;flex flex-col md:flex-row items-center border p-4 rounded&quot;<br>          &gt;<br>            &lt;div className=&quot;flex-1 flex flex-col items-center&quot;&gt;<br>              &lt;p className=&quot;font-bold mb-2&quot;&gt;Original&lt;/p&gt;<br>              &lt;img<br>                src={img.originalUrl}<br>                alt=&quot;Original&quot;<br>                className=&quot;w-32 h-32 object-cover rounded border mb-2&quot;<br>              /&gt;<br>              &lt;p className=&quot;text-sm&quot;&gt;Size: {formatBytes(img.file.size)}&lt;/p&gt;<br>            &lt;/div&gt;<br>            {img.status === &#39;done&#39; &amp;&amp; img.compressedUrl ? (<br>              &lt;div className=&quot;flex-1 flex flex-col items-center mt-4 md:mt-0&quot;&gt;<br>                &lt;p className=&quot;font-bold mb-2&quot;&gt;Compressed&lt;/p&gt;<br>                &lt;img<br>                  src={img.compressedUrl}<br>                  alt=&quot;Compressed&quot;<br>                  className=&quot;w-32 h-32 object-cover rounded border mb-2&quot;<br>                /&gt;<br>                &lt;p className=&quot;text-sm&quot;&gt;<br>                  Size:{&#39; &#39;}<br>                  {img.compressedSize ? formatBytes(img.compressedSize) : &#39;N/A&#39;}<br>                &lt;/p&gt;<br>                &lt;a<br>                  href={img.compressedUrl}<br>                  download={`${img.file.name.replace(<br>                    /\.[^/.]+$/,<br>                    &#39;&#39;<br>                  )}-compressed.webp`}<br>                  className=&quot;mt-2 inline-block px-3 py-1 bg-blue-500 text-white rounded&quot;<br>                &gt;<br>                  Download<br>                &lt;/a&gt;<br>              &lt;/div&gt;<br>            ) : img.status === &#39;compressing&#39; ? (<br>              &lt;div className=&quot;flex-1 flex flex-col items-center mt-4 md:mt-0&quot;&gt;<br>                &lt;p className=&quot;font-bold&quot;&gt;Compressing...&lt;/p&gt;<br>              &lt;/div&gt;<br>            ) : img.status === &#39;error&#39; ? (<br>              &lt;div className=&quot;flex-1 flex flex-col items-center mt-4 md:mt-0&quot;&gt;<br>                &lt;p className=&quot;font-bold text-red-500&quot;&gt;Error in compression&lt;/p&gt;<br>              &lt;/div&gt;<br>            ) : null}<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ImageList;</pre><p>The ImageList component takes one prop, images, which is a list of ImgData. It then displays the original and compressed images, showing their size and providing a download option for the compressed images.</p><p>Next, update the app/page.tsx with the following code, and let&#39;s go through the parts together.</p><pre>&#39;use client&#39;;<br><br>import { useState, useRef, useEffect } from &#39;react&#39;;<br>import ImageList, { ImgData } from &#39;../components/ImageList&#39;;<br><br>export default function Home() {<br>  const [images, setImages] = useState&lt;ImgData[]&gt;([]);<br>  const [text, setText] = useState(&#39;&#39;);<br><br>  const workerRef = useRef&lt;Worker | null&gt;(null);<br><br>  const handleFileChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    const files = e.target.files;<br>    if (!files || !workerRef.current) return;<br>    const filesArray = Array.from(files);<br>    filesArray.forEach((file, index) =&gt; {<br>      const id = Date.now() + index;<br><br>      const originalUrl = URL.createObjectURL(file);<br>      setImages((prev) =&gt; [<br>        ...prev,<br>        { id, file, status: &#39;compressing&#39;, originalUrl },<br>      ]);<br><br>      // Send the file with its id to the worker.<br>      workerRef.current!.postMessage({<br>        id,<br>        imageFile: file,<br>        options: { quality: 75 },<br>      });<br>    });<br>  };<br><br>  // Initialize the worker once when the component mounts.<br>  useEffect(() =&gt; {<br>    const worker = new Worker(<br>      new URL(&#39;../worker/imageCompressionWorker.ts&#39;, import.meta.url),<br>      { type: &#39;module&#39; }<br>    );<br>    workerRef.current = worker;<br><br>    // Listen for messages from the worker.<br>    worker.onmessage = (<br>      event: MessageEvent&lt;{ id: number; blob?: Blob; error?: string }&gt;<br>    ) =&gt; {<br>      const { id, blob: compressedBlob, error } = event.data;<br>      setImages((prev) =&gt;<br>        prev.map((img) =&gt; {<br>          if (img.id === id) {<br>            if (error) return { ...img, status: &#39;error&#39;, error };<br>            const compressedSize = compressedBlob!.size;<br>            const compressedUrl = URL.createObjectURL(compressedBlob!);<br>            return { ...img, status: &#39;done&#39;, compressedUrl, compressedSize };<br>          }<br>          return img;<br>        })<br>      );<br>    };<br><br>    return () =&gt; {<br>      worker.terminate();<br>    };<br>  }, []);<br><br>  return (<br>    &lt;div className=&quot;min-h-screen p-8&quot;&gt;<br>      &lt;h1 className=&quot;text-2xl font-bold text-center mb-4&quot;&gt;<br>        Image Compression with Web Workers<br>      &lt;/h1&gt;<br>      &lt;div className=&quot;rounded shadow p-4 mb-4 flex flex-col gap-2&quot;&gt;<br>        &lt;p className=&quot;text-sm&quot;&gt;<br>          While images are compressing, you can interact with the textarea below<br>          and observe the text being typed and UI is not frozen.<br>        &lt;/p&gt;<br>        &lt;p className=&quot;text-sm&quot;&gt;<br>          Even you can open the dev tools and then open the performance tab and<br>          see the INP(Interaction to Next Paint) is very low.<br>        &lt;/p&gt;<br>        &lt;textarea<br>          className=&quot;w-full h-32 border rounded p-2 text-black&quot;<br>          placeholder=&quot;Type here while images are compressing...&quot;<br>          value={text}<br>          onChange={(e) =&gt; setText(e.target.value)}<br>        &gt;&lt;/textarea&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;rounded shadow p-4&quot;&gt;<br>        &lt;input<br>          type=&quot;file&quot;<br>          multiple<br>          accept=&quot;image/webp&quot;<br>          onChange={handleFileChange}<br>        /&gt;<br>        &lt;ImageList images={images} /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>First, we import the hooks and the ImageList component, along with ImgData for type.</p><pre>import { useState, useRef, useEffect } from &#39;react&#39;;<br>import ImageList, { ImgData } from &#39;../components/ImageList&#39;;</pre><p>Then, we create a ref to hold the worker instance because we don’t want to create the worker repeatedly with each re-render. We also want to avoid re-rendering the component if the worker instance changes.</p><pre>const workerRef = useRef&lt;Worker | null&gt;(null);</pre><p>In the useEffect, we are initializing the worker instance by using the imageCompressionWorker.ts worker script we created earlier.</p><blockquote><em>We use the URL API with </em><em>import.meta.url. This makes the path relative to the current script instead of the HTML page. This way, the bundler can safely optimize, like renaming, because otherwise, the </em><em>worker.js URL might point to a file not managed by the bundler, stopping it from making assumptions. Read more </em><a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#url"><em>here</em></a><em>.</em></blockquote><p>Once the worker is initialized, we listen for messages from it. When we receive a message, we extract the id, blob, and error, then update the images state with the new values.</p><p>Finally, we clean up the worker when the component unmounts.</p><pre>useEffect(() =&gt; {<br>    const worker = new Worker(<br>      new URL(&#39;../worker/imageCompressionWorker.ts&#39;, import.meta.url),<br>      { type: &#39;module&#39; }<br>    );<br>    workerRef.current = worker;<br><br>    // Listen for messages from the worker.<br>    worker.onmessage = (<br>      event: MessageEvent&lt;{ id: number; blob?: Blob; error?: string }&gt;<br>    ) =&gt; {<br>      const { id, blob: compressedBlob, error } = event.data;<br>      setImages((prev) =&gt;<br>        prev.map((img) =&gt; {<br>          if (img.id === id) {<br>            if (error) return { ...img, status: &#39;error&#39;, error };<br>            const compressedSize = compressedBlob!.size;<br>            const compressedUrl = URL.createObjectURL(compressedBlob!);<br>            return { ...img, status: &#39;done&#39;, compressedUrl, compressedSize };<br>          }<br>          return img;<br>        })<br>      );<br>    };<br><br>    return () =&gt; {<br>      worker.terminate();<br>    };<br>  }, []);</pre><p>To manage image file uploads, we use the handleFileChange method. This method listens for the onchange event of the file input, processes the files, and sends them to the worker for compression.</p><pre>const handleFileChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    const files = e.target.files;<br>    if (!files || !workerRef.current) return;<br>    const filesArray = Array.from(files);<br>    filesArray.forEach((file, index) =&gt; {<br>      const id = Date.now() + index;<br><br>      const originalUrl = URL.createObjectURL(file);<br>      setImages((prev) =&gt; [<br>        ...prev,<br>        { id, file, status: &#39;compressing&#39;, originalUrl },<br>      ]);<br><br>      // Send the file with its id to the worker.<br>      workerRef.current!.postMessage({<br>        id,<br>        imageFile: file,<br>        options: { quality: 75 },<br>      });<br>    });<br>  };</pre><p>Finally, render the elements the textarea, image input, and image list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*30WBYPwqNZ3Z2hbv.png" /></figure><ul><li><strong>User Selects Images:</strong> The user picks images using the file input, which makes the component create object URLs and mark each image as “compressing.”</li><li><strong>Worker Communication:</strong> The component sends each image file (with options) to the Web Worker.</li><li><strong>Parallel Processes:</strong></li><li><strong>Text Area Interaction:</strong> At the same time, the user can type in the text area, showing that the UI is not blocked.</li><li><strong>Image Compression:</strong> The worker compresses the image in the background.</li><li><strong>Completion:</strong> When compression is done, the worker sends the result back to the component, which updates the UI with the compressed image while the text area keeps working smoothly.</li></ul><p>Great, everything is set up. In the next section, we will run the application and see how the web worker works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*sQ-7EjPSZSulo6J3.gif" /></figure><h3>Running the example</h3><p>Open the terminal and run the command below, then go to <a href="http://localhost:3000/">http://localhost:3000/</a>.</p><pre>npm run dev</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*GJQqyulplc4F1Ruc.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*HyIj1ik43zqzIK4D.png" /></figure><p>Try the live demo here: <a href="https://web-worker-with-example.vercel.app/">https://web-worker-with-example.vercel.app/</a></p><h3>Conclusion</h3><p>Web workers are a great tool to improve application performance. By using Web Workers, you ensure <strong>faster, smoother, and more responsive applications</strong>. However, they should not be overused and should only be used when necessary. Also, check browser support, which is currently about 98% globally. You can check it <a href="https://caniuse.com/?search=webworkers">here</a>.</p><p>That’s all for this topic. Thank you for reading! If you found this article helpful, please consider liking, commenting, and sharing it with others.</p><h3>Resources</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Using web workers</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#browser_compatibility">Web worker Browser Compatibility</a></li><li><a href="https://github.com/Sachin-chaurasiya/web-worker-with-example">Source Code</a></li><li><a href="https://github.com/jamsinclair/jSquash/tree/main/packages/webp">Jsquash webp doc</a></li></ul><p><em>Originally published at </em><a href="https://dev.to/sachinchaurasiya/how-web-worker-works-with-a-practical-example-c98"><em>https://dev.to</em></a><em> on February 23, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16c85b308df0" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/how-web-worker-works-with-a-practical-example-16c85b308df0">How web worker works with a practical example</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[How to Build a Collaborative Editor with Next.js and Liveblocks]]></title>
            <link>https://blog.stackademic.com/how-to-build-a-collaborative-editor-with-next-js-and-liveblocks-c9018faf1024?source=rss-74fad1116d0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9018faf1024</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[wev-development]]></category>
            <dc:creator><![CDATA[Sachin Chaurasiya]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 18:53:32 GMT</pubDate>
            <atom:updated>2024-12-19T07:24:03.192Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1r6ECp-pqz8tarua9e5oQ.png" /></figure><p>Collaborative applications are now essential in modern software, allowing multiple users to work on the same document, design, or codebase at the same time. Think of Google Docs, Figma, or multiplayer coding platforms these tools are powerful because they offer <strong>real-time collaboration</strong>, where every change is instantly visible to everyone.</p><p>In this guide, I’ll show you how to build a collaborative text editor using <strong>Next.js</strong> and <strong>Liveblocks</strong>, a library that makes real-time collaboration easy. By the end, you’ll have a working editor where multiple users can edit a document, see each other’s changes in real-time, and track who is online and what they are doing.</p><h3>What to Expect from This Guide?</h3><h4>Part 1: Understanding Collaborative Editors and the Role of Liveblocks</h4><p>In the first part, we’ll look at what collaborative editors are, how they work, and the technologies behind them. We’ll focus on <strong>WebSockets</strong> for real-time updates and discuss how <strong>Liveblocks</strong> makes building these features easier.</p><h4>Part 2: Building the Collaborative Editor Step-by-Step</h4><p>In the second part, we’ll start building the editor from scratch. We’ll set up the project, integrate Liveblocks, and add features like real-time editing, user presence indicators, and managing document state. By the end, you’ll have a live, shareable editor to show off.</p><p>Ready to get started? First, let’s understand the basics of collaborative editors, the technology behind them, and why Liveblocks is perfect for building them.</p><h3>What is a Collaborative Editor?</h3><p>Imagine you’re editing a document with a friend. You both see each other’s changes in real-time, making it feel like you’re working on the same computer. That’s the magic of collaborative editors.</p><p>A collaborative editor is a software tool that lets multiple users work on the same document or file at the same time. Each user can make changes, and everyone sees these updates instantly. Examples include Google Docs, Notion, and Figma.</p><h3>How Do Collaborative Editors Work?</h3><p>Collaborative editors use <strong>real-time communication</strong> between users and a shared server. Here’s a simple overview of how it works</p><ol><li>When a user edits the document, the changes are sent to the server.</li><li>The server processes these changes and sends them to all connected users.</li><li>Everyone’s view updates instantly, showing the changes in real-time.</li></ol><p>In scenarios where multiple users make changes simultaneously, the editor must effectively manage these updates to ensure consistency. This is where the technology that enables this real-time synchronization comes into play: <strong>WebSockets</strong>.</p><h3>The Technology Behind Real-Time Collaboration: WebSockets</h3><p>Most traditional websites use HTTP requests to talk to servers. This works well for static pages but isn’t quick enough for real-time apps like collaborative editors.</p><p><strong>WebSockets</strong> fix this by allowing ongoing, two-way communication between the client and the server. Instead of sending separate requests for every update, a WebSocket connection stays <strong>open</strong>. This way, data can be sent and received instantly as changes occur.</p><p>Here’s a simple explanation of how WebSocket communication works</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*hshctYMiW5YZQOqH.png" /></figure><ol><li>User 1 makes an edit.</li><li>The server gets the edit and sends it to both User 1 and User 2.</li><li>User 2 makes an edit, and the server sends it to both users again.</li></ol><p>This way, everyone sees the same document version in real-time.</p><h3>Liveblocks: Simplifying Real-Time Collaboration</h3><p>Building a collaborative editor from scratch is possible, but handling real-time sync, conflict resolution, and user presence can be tricky. This is where <strong>Liveblocks</strong> helps.</p><p><strong>Liveblocks</strong> is a powerful library that makes building collaborative apps easier. Instead of writing all the WebSocket and state management code yourself, you can use Liveblocks’ built-in features, such as</p><ul><li><strong>Presence</strong>: Track who is online and what they are doing.</li><li><strong>Storage</strong>: Share and sync documents, drawings, or any content.</li><li><strong>Room Management</strong>: Manage connections and permissions for multiple users.</li></ul><p>Here’s why using Liveblocks can save you a lot of time:</p><ol><li><strong>Built-in Presence</strong>: See who’s editing, where their cursors are, and what they’re typing all in real-time.</li><li><strong>Conflict Handling</strong>: Easily manage updates when multiple users make changes at the same time.</li><li><strong>Simple Integration</strong>: It works seamlessly with popular frontend frameworks like Next.js, making it easier to build and scale.</li></ol><p>By using Liveblocks, you can focus on building the core features of your editor without worrying about low-level communication details.</p><h3>Project Setup</h3><p>Let’s start by creating a new Next.js project.</p><pre>npx create-next-app@latest collaborative-editor --typescript</pre><p>After creating the project install the Liveblocks dependencies</p><pre>npm install @liveblocks/client @liveblocks/node @liveblocks/react @liveblocks/yjs @tiptap/extension-collaboration @tiptap/extension-collaboration-cursor @tiptap/pm @tiptap/react @tiptap/starter-kit yjs</pre><p>Next, create a Liveblocks config to set up the types for the user information and to display the cursor in the editor.</p><pre>// liveblocks.config.ts<br><br>declare global {<br>  interface Liveblocks {<br>    Presence: { cursor: { x: number; y: number } | null };<br>    UserMeta: {<br>      id: string;<br>      info: {<br>        name: string;<br>        color: string;<br>        picture: string;<br>      };<br>    };<br>  }<br>}<br><br>export {};</pre><p>Go to <a href="https://liveblocks.io/">https://liveblocks.io/</a> and sign up for a free account. After signing up, you’ll be taken to the dashboard where you will see two projects created for you. Select the first project, go to the API keys section on the left panel, and get the secret key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*y0w0xCU1MyjAp42a.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*xMRMhEC81KVrV5oU.png" /></figure><p>Create a .env file and add LIVEBLOCKS_SECRET_KEY environment variable and secret key you copied from the API keys dashboard.</p><pre>LIVEBLOCKS_SECRET_KEY=sk_dev_xxxxxxxxxx_xxxxxxx_xxx_xxxxx_x</pre><p>Alright, the project setup is done. In the next section, we will create components for our editor.</p><h3>Create components for the editor</h3><blockquote><em>I won’t talk about styling because this post is about building a collaborative editor with Liveblocks and Next.js. I’ll share a GitHub link for the CSS and icon files.</em></blockquote><blockquote><a href="https://github.com/Sachin-chaurasiya/collaborative-editor/tree/main/src/components"><em>Here is the link for all components, their CSS files, and icons</em></a></blockquote><p>Let’s start by creating a toolbar component and adding the following code. We will use Tiptap to build the editor because it is one of my favorite tools for creating rich text and collaborative editors.</p><pre>// components/Toolbar.tsx<br><br>import { Editor } from &quot;@tiptap/react&quot;;<br>import styles from &quot;./Toolbar.module.css&quot;;<br><br>type Props = {<br>  editor: Editor | null;<br>};<br><br>export function Toolbar({ editor }: Props) {<br>  if (!editor) {<br>    return null;<br>  }<br><br>  return (<br>    &lt;div className={styles.toolbar}&gt;<br>      &lt;button<br>        className={styles.button}<br>        onClick={() =&gt; editor.chain().focus().toggleBold().run()}<br>        data-active={editor.isActive(&quot;bold&quot;) ? &quot;is-active&quot; : undefined}<br>        aria-label=&quot;bold&quot;<br>      &gt;<br>        &lt;BoldIcon /&gt;<br>      &lt;/button&gt;<br>      &lt;button<br>        className={styles.button}<br>        onClick={() =&gt; editor.chain().focus().toggleItalic().run()}<br>        data-active={editor.isActive(&quot;italic&quot;) ? &quot;is-active&quot; : undefined}<br>        aria-label=&quot;italic&quot;<br>      &gt;<br>        &lt;ItalicIcon /&gt;<br>      &lt;/button&gt;<br>      &lt;button<br>        className={styles.button}<br>        onClick={() =&gt; editor.chain().focus().toggleStrike().run()}<br>        data-active={editor.isActive(&quot;strike&quot;) ? &quot;is-active&quot; : undefined}<br>        aria-label=&quot;strikethrough&quot;<br>      &gt;<br>        &lt;StrikethroughIcon /&gt;<br>      &lt;/button&gt;<br><br>      &lt;button<br>        className={styles.button}<br>        onClick={() =&gt; editor.chain().focus().toggleBlockquote().run()}<br>        data-active={editor.isActive(&quot;blockquote&quot;) ? &quot;is-active&quot; : undefined}<br>        aria-label=&quot;strikethrough&quot;<br>      &gt;<br>        &lt;BlockQuoteIcon /&gt;<br>      &lt;/button&gt;<br><br>      &lt;button<br>        className={styles.button}<br>        onClick={() =&gt; editor.chain().focus().setHorizontalRule().run()}<br>        data-active={undefined}<br>        aria-label=&quot;horizontal-line&quot;<br>      &gt;<br>        &lt;HorizontalLineIcon /&gt;<br>      &lt;/button&gt;<br><br>      &lt;button<br>        className={styles.button}<br>        onClick={() =&gt; editor.chain().focus().toggleBulletList().run()}<br>        data-active={editor.isActive(&quot;bulletList&quot;) ? &quot;is-active&quot; : undefined}<br>        aria-label=&quot;bullet-list&quot;<br>      &gt;<br>        &lt;BulletListIcon /&gt;<br>      &lt;/button&gt;<br><br>      &lt;button<br>        className={styles.button}<br>        onClick={() =&gt; editor.chain().focus().toggleOrderedList().run()}<br>        data-active={editor.isActive(&quot;orderedList&quot;) ? &quot;is-active&quot; : undefined}<br>        aria-label=&quot;number-list&quot;<br>      &gt;<br>        &lt;OrderedListIcon /&gt;<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Here we are using the Tiptap editor and its formatting options like italic, bold, and lists.</p><p>Next, let’s create an Avatars component to display all the online users in the room.</p><pre>// components/Avatars.tsx<br><br>import { useOthers, useSelf } from &quot;@liveblocks/react/suspense&quot;;<br>import styles from &quot;./Avatars.module.css&quot;;<br><br>export function Avatars() {<br>  const users = useOthers();<br>  const currentUser = useSelf();<br><br>  return (<br>    &lt;div className={styles.avatars}&gt;<br>      {users.map(({ connectionId, info }) =&gt; {<br>        return (<br>          &lt;Avatar key={connectionId} picture={info.picture} name={info.name} /&gt;<br>        );<br>      })}<br><br>      {currentUser &amp;&amp; (<br>        &lt;div className=&quot;relative ml-8 first:ml-0&quot;&gt;<br>          &lt;Avatar<br>            picture={currentUser.info.picture}<br>            name={currentUser.info.name}<br>          /&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export function Avatar({ picture, name }: { picture: string; name: string }) {<br>  return (<br>    &lt;div className={styles.avatar} data-tooltip={name}&gt;<br>      &lt;img<br>        src={picture}<br>        className={styles.avatar_picture}<br>        data-tooltip={name}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Here we are using two hooks:</p><ul><li>useOthers: to get the list of other users connected to the same room I&#39;m in.</li><li>useSelf: to get the info of my own user</li></ul><p>Now let’s create an ErrorListener component to catch any errors happening inside the Liveblocks provider. most important one is the 4001 when user is trying to connect the room which they don’t have access to.</p><pre>// components/ErrorListener.tsx<br><br>&quot;use client&quot;;<br>import { useErrorListener } from &quot;@liveblocks/react/suspense&quot;;<br>import React from &quot;react&quot;;<br>import styles from &quot;./ErrorListener.module.css&quot;;<br>import { Loading } from &quot;./Loading&quot;;<br>const ErrorListener = () =&gt; {<br>  const [error, setError] = React.useState&lt;string | undefined&gt;();<br>  useErrorListener((error) =&gt; {<br>    switch (error.code) {<br>      case -1:<br>        setError(&quot;Could not connect to Liveblocks&quot;);<br>        break;<br>      case 4001:<br>        // Could not connect because you don&#39;t have access to this room<br>        setError(&quot;You don&#39;t have access to this room&quot;);<br>        break;<br>      default:<br>        setError(&quot;An unexpected error occurred&quot;);<br>        break;<br>    }<br>  });<br>  return error ? (<br>    &lt;div className={styles.container}&gt;<br>      &lt;div className={styles.error}&gt;{error}&lt;/div&gt;<br>    &lt;/div&gt;<br>  ) : (<br>    &lt;Loading /&gt;<br>  );<br>};<br>export default ErrorListener;</pre><p>Thanks to Liveblocks for making things easier with the useErrorListener hook, which handles all the error-catching logic in our collaborative application.</p><p>Next is the ConnectToRoom component, which shows the initial UI where the user enters the room name they want to join. Then, it redirects to the room page using the entered name as the roomId.</p><pre>// components/ConnectToRoom.tsx<br>&quot;use client&quot;;<br>import React from &quot;react&quot;;<br>import styles from &quot;./ConnectToRoom.module.css&quot;;<br>import { useRouter } from &quot;next/navigation&quot;;<br>const ConnectToRoom = () =&gt; {<br>  const router = useRouter();<br>  const inputRef = React.useRef&lt;HTMLInputElement&gt;(null);<br>  const connectToRoom = async () =&gt; {<br>    const roomId = inputRef.current?.value;<br>    if (roomId &amp;&amp; roomId.length &gt; 0) {<br>      await (async () =&gt; router.push(`/room?roomId=${roomId}`))();<br>    }<br>  };<br>  return (<br>    &lt;div className={styles.container}&gt;<br>      &lt;h1&gt;Connect to a room&lt;/h1&gt;<br>      &lt;p&gt;Connect to a room to start collaborating with others.&lt;/p&gt;<br>      &lt;input<br>        ref={inputRef}<br>        type=&quot;text&quot;<br>        placeholder=&quot;Room ID&quot;<br>        className={styles.input}<br>      /&gt;<br>      &lt;button className={styles.button} onClick={connectToRoom}&gt;<br>        Connect<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>export default ConnectToRoom;</pre><p>Since we will get the roomId from the URL, let’s create a custom hook.</p><pre>// hooks/useRoomId.ts<br><br>import { useSearchParams } from &quot;next/navigation&quot;;<br>import { useEffect, useState } from &quot;react&quot;;<br>export const useRoomId = () =&gt; {<br>  const searchParams = useSearchParams();<br>  const [roomId, setRoomId] = useState&lt;string | null&gt;(<br>    searchParams.get(&quot;roomId&quot;)<br>  );<br>  useEffect(() =&gt; {<br>    setRoomId(searchParams.get(&quot;roomId&quot;));<br>  }, [searchParams]);<br>  return roomId;<br>};</pre><p>Lastly, there’s the Editor component, which works together with Tiptap and Liveblocks to create some of the magic.</p><pre>// components/Editor.tsx<br><br>&quot;use client&quot;;<br>import { useEditor, EditorContent } from &quot;@tiptap/react&quot;;<br>import StarterKit from &quot;@tiptap/starter-kit&quot;;<br>import Collaboration from &quot;@tiptap/extension-collaboration&quot;;<br>import CollaborationCursor from &quot;@tiptap/extension-collaboration-cursor&quot;;<br>import * as Y from &quot;yjs&quot;;<br>import { LiveblocksYjsProvider } from &quot;@liveblocks/yjs&quot;;<br>import { useRoom, useSelf } from &quot;@liveblocks/react/suspense&quot;;<br>import { useEffect, useState } from &quot;react&quot;;<br>import { Toolbar } from &quot;./Toolbar&quot;;<br>import styles from &quot;./Editor.module.css&quot;;<br>import { Avatars } from &quot;@/components/Avatars&quot;;<br>export function Editor() {<br>  const room = useRoom();<br>  const [doc, setDoc] = useState&lt;Y.Doc&gt;();<br>  const [provider, setProvider] = useState&lt;any&gt;();<br>  useEffect(() =&gt; {<br>    const yDoc = new Y.Doc();<br>    const yProvider = new LiveblocksYjsProvider(room, yDoc);<br>    setDoc(yDoc);<br>    setProvider(yProvider);<br>    return () =&gt; {<br>      yDoc?.destroy();<br>      yProvider?.destroy();<br>    };<br>  }, [room]);<br>  if (!doc || !provider) {<br>    return null;<br>  }<br>  return &lt;TiptapEditor doc={doc} provider={provider} /&gt;;<br>}<br>type EditorProps = {<br>  doc: Y.Doc;<br>  provider: any;<br>};<br>function TiptapEditor({ doc, provider }: EditorProps) {<br>  const userInfo = useSelf((me) =&gt; me.info);<br>  const editor = useEditor({<br>    editorProps: {<br>      attributes: {<br>        class: styles.editor,<br>      },<br>    },<br>    extensions: [<br>      StarterKit.configure({<br>        history: false,<br>      }),<br>      Collaboration.configure({<br>        document: doc,<br>      }),<br>      CollaborationCursor.configure({<br>        provider: provider,<br>        user: userInfo,<br>      }),<br>    ],<br>  });<br>  return (<br>    &lt;div className={styles.container}&gt;<br>      &lt;div className={styles.editorHeader}&gt;<br>        &lt;Toolbar editor={editor} /&gt;<br>        &lt;Avatars /&gt;<br>      &lt;/div&gt;<br>      &lt;EditorContent editor={editor} className={styles.editorContainer} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*k-du1DyM-UIzHhhk.png" /></figure><p>Liveblocks gives us a YJS provider that helps define and store the editor content. Plus, Tiptap supports collaboration extensions, making it easy to set up collaboration.</p><p>Great, our editor is ready, but for collaboration, we need to set up the Liveblocks provider and RoomProvider. This will allow users to authenticate themselves and create a session for the room they want to join.</p><p>In the next section, we will discuss rooms and how Liveblocks enable real-time collaboration.</p><h3>Set Up Liveblocks Provider and Room Provider</h3><p>Before writing the code let’s first understand how Liveblocks work with the diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*IN0QxnW_OWIf-Hhj.png" /></figure><ul><li>When a user opens the app, it sends a request to find out which room they want to join. The room ID is obtained using the useRoomId hook.</li><li>After getting the roomId, the LiveblocksProvider is set up.</li><li>An authentication request is sent to /api/liveblocks-auth (we will set this up soon) with the roomId to check the user&#39;s access.</li><li>If the authentication is successful, the room setup starts. This includes creating a new collaborative document instance (Y.Doc) and setting up a provider (LiveblocksYjsProvider) to handle synchronization with the Liveblocks backend.</li><li>The LiveblocksYjsProvider opens a WebSocket connection with Liveblocks, joining the specified room.</li><li>The initial presence state (like cursor position and user activity) is shared with other participants in the room.</li><li><strong>User Presence</strong>: When a user joins, their presence is updated and shared with everyone in the room.</li><li><strong>Cursor Tracking</strong>: Their cursor position is tracked and shared instantly using the CollaborationCursor extension.</li><li><strong>Document Synchronization</strong>: Any changes a user makes are sent to the Liveblocks server, which updates the shared document for all users.</li><li>If <strong>User A</strong> edits the document, these changes are sent to Liveblocks as updates.</li><li>Liveblocks sends these changes to all users, keeping the document in sync.</li><li>When <strong>User B</strong> joins, their cursor and presence are shared with everyone.</li><li>When a user leaves, the Y.Doc instance and provider are removed, and the WebSocket connection is closed.</li><li>This starts a cleanup process to remove the user’s presence and updates from the room.</li></ul><p>I hope the explanation above helps you understand how Liveblocks works.</p><p>As mentioned, Liveblocks needs an endpoint to verify the user and start a session for the room they want to join. So, let’s create an API endpoint called liveblocks-auth.</p><pre>// app/api/liveblocks-auth/route.ts<br><br>import { Liveblocks } from &quot;@liveblocks/node&quot;;<br>import { NextRequest } from &quot;next/server&quot;;<br>const liveblocks = new Liveblocks({<br>  secret: process.env.LIVEBLOCKS_SECRET_KEY!,<br>});<br>export async function POST(request: NextRequest) {<br>  const userId = Math.floor(Math.random() * 10) % USER_INFO.length;<br>  const roomId = request.nextUrl.searchParams.get(&quot;roomId&quot;);<br>  const session = liveblocks.prepareSession(`session-${userId}`, {<br>    userInfo: USER_INFO[userId],<br>  });<br>  session.allow(roomId!, session.FULL_ACCESS);<br>  const { body, status } = await session.authorize();<br>  return new Response(body, { status });<br>}<br>const USER_INFO = [<br>  {<br>    name: &quot;Sachin Chaurasiya&quot;,<br>    color: &quot;#D583F0&quot;,<br>    picture: &quot;https://github.com/Sachin-chaurasiya.png&quot;,<br>  },<br>  {<br>    name: &quot;Mislav Abha&quot;,<br>    color: &quot;#F08385&quot;,<br>    picture: &quot;https://liveblocks.io/avatars/avatar-2.png&quot;,<br>  },<br>  {<br>    name: &quot;Tatum Paolo&quot;,<br>    color: &quot;#F0D885&quot;,<br>    picture: &quot;https://liveblocks.io/avatars/avatar-3.png&quot;,<br>  },<br>  {<br>    name: &quot;Anjali Wanda&quot;,<br>    color: &quot;#85EED6&quot;,<br>    picture: &quot;https://liveblocks.io/avatars/avatar-4.png&quot;,<br>  },<br>  {<br>    name: &quot;Jody Hekla&quot;,<br>    color: &quot;#85BBF0&quot;,<br>    picture: &quot;https://liveblocks.io/avatars/avatar-5.png&quot;,<br>  },<br>  {<br>    name: &quot;Emil Joyce&quot;,<br>    color: &quot;#8594F0&quot;,<br>    picture: &quot;https://liveblocks.io/avatars/avatar-6.png&quot;,<br>  },<br>  {<br>    name: &quot;Jory Quispe&quot;,<br>    color: &quot;#85DBF0&quot;,<br>    picture: &quot;https://liveblocks.io/avatars/avatar-7.png&quot;,<br>  },<br>  {<br>    name: &quot;Quinn Elton&quot;,<br>    color: &quot;#87EE85&quot;,<br>    picture: &quot;https://liveblocks.io/avatars/avatar-8.png&quot;,<br>  },<br>];</pre><p>Here, we are using fake user data, but in a real product, you would get the user data from the database and then create the session.</p><p>This line lets the user access the room with full permissions, which are room:read and room:write. This is just for demo purposes, but in real situations, access will depend on the user&#39;s role.</p><pre>session.allow(roomId!, session.FULL_ACCESS);</pre><p>Next, Let’s create a Provider component and use it in the RootLayout.</p><pre>// app/Providers.tsx<br><br>&quot;use client&quot;;<br>import { useRoomId } from &quot;@/hooks/useRoomId&quot;;<br>import { LiveblocksProvider } from &quot;@liveblocks/react&quot;;<br>import { type PropsWithChildren } from &quot;react&quot;;<br>export function Providers({ children }: PropsWithChildren) {<br>  const roomId = useRoomId();<br>  return (<br>    &lt;LiveblocksProvider<br>      key={roomId}<br>      authEndpoint={`/api/liveblocks-auth?roomId=${roomId}`}<br>    &gt;<br>      {children}<br>    &lt;/LiveblocksProvider&gt;<br>  );<br>}</pre><p>Update the root layout and wrap the children with the providers.</p><pre>// app/layout.tsx<br>import { Providers } from &quot;./Providers&quot;;<br>...<br><br>return (<br>    ...<br>    &lt;body&gt;<br>      &lt;Providers&gt;{children}&lt;/Providers&gt;<br>    &lt;/body&gt;<br>    ...<br>)</pre><p>Alright, the providers are set up. Now, let’s create a Room component using RoomProvider.</p><pre>// app/Room.tsx<br><br>&quot;use client&quot;;<br><br>import { ReactNode } from &quot;react&quot;;<br>import { RoomProvider } from &quot;@liveblocks/react/suspense&quot;;<br>import { ClientSideSuspense } from &quot;@liveblocks/react&quot;;<br>import ErrorListener from &quot;@/components/ErrorListener&quot;;<br>import { useRoomId } from &quot;@/hooks/useRoomId&quot;;<br><br>export function Room({ children }: { children: ReactNode }) {<br>  const roomId = useRoomId();<br><br>  return (<br>    &lt;RoomProvider<br>      id={roomId ?? &quot;&quot;}<br>      initialPresence={{<br>        cursor: null,<br>      }}<br>      key={roomId}<br>    &gt;<br>      &lt;ClientSideSuspense fallback={&lt;ErrorListener /&gt;}&gt;<br>        {children}<br>      &lt;/ClientSideSuspense&gt;<br>    &lt;/RoomProvider&gt;<br>  );<br>}</pre><p>Here, RoomProvider uses two props: roomId and initialPresence for the user&#39;s cursor, which is just the x, y position of the cursor.</p><p>We use ClientSideSuspense with the ErrorListener component as a fallback. If there&#39;s an error, it will show the error; otherwise, it will display a loader, meaning the providers are still loading.</p><p>Next, create the Room page and add the following code. It’s straightforward: use the Room component to wrap the Editor so that the editor gets all the connections in that specific room.</p><pre>// app/room/page.tsx<br>&quot;use client&quot;;<br>import { Room } from &quot;@/app/Room&quot;;<br>import { Editor } from &quot;@/components/Editor&quot;;<br>export default function RoomPage() {<br>  return (<br>    &lt;main&gt;<br>      &lt;Room&gt;<br>        &lt;Editor /&gt;<br>      &lt;/Room&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>Finally, update the Home page, which is app/page.tsx.</p><pre>import ConnectToRoom from &quot;@/components/ConnectToRoom&quot;;<br><br>export default function Home() {<br>  return (<br>    &lt;main&gt;<br>      &lt;ConnectToRoom /&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>Alright, Liveblocks providers are set up correctly. Now, let’s move on to the most exciting part: testing our collaborative editor. Are you excited? I am too! Let’s test it in the next section.</p><h3>Testing</h3><p>Start the dev server by running the following command</p><pre>npm run dev</pre><p>The server will start on localhost:3000, and you will see the “Connect to Room” interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*9ozNZpND0ClI6qfd.png" /></figure><p>Enter the room ID, and you will be taken to the room page where you can work with other users in real time.</p><p>Here is an example of two users connecting to the same room, local-room.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*UgBVMkbLYly5K7e1.gif" /></figure><p>Great job, and congratulations on building the editor with real-time collaboration.</p><p>Thanks for reading to the end. If you don’t want to miss interesting topics and project-building content, subscribe to the <a href="https://devbuddyweekly.substack.com/">Dev Buddy newsletter</a>.</p><h3>Conclusion</h3><p>In this guide, we explore the power of collaborative applications, focusing on building a real-time collaborative text editor using Next.js and Liveblocks.</p><p>We break down the process into understanding the role of collaborative editors and setting up a project with features like real-time editing, user presence tracking, and document state management.</p><h3>Resources</h3><ul><li><a href="https://github.com/Sachin-chaurasiya/collaborative-editor">GitHub Repo</a></li><li>Thanks to Liveblocks for creating different examples <a href="https://github.com/liveblocks/liveblocks/tree/main/examples">here</a></li></ul><p><em>Originally Published at </em><a href="https://devbuddyweekly.substack.com/p/how-to-build-a-collaborative-editor"><em>DevBuddyWeekly</em></a></p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li><li>Have a story to share? <a href="https://formulatools.co/f/cJh1CStlo9jJmhIegBM9"><strong>Join our global community of writers today!</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9018faf1024" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-build-a-collaborative-editor-with-next-js-and-liveblocks-c9018faf1024">How to Build a Collaborative Editor with Next.js and Liveblocks</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Broadcast Channel API in React]]></title>
            <link>https://javascript.plainenglish.io/how-to-use-broadcast-channel-api-in-react-bc19c7a7c358?source=rss-74fad1116d0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc19c7a7c358</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sachin Chaurasiya]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 06:32:50 GMT</pubDate>
            <atom:updated>2024-09-22T16:59:46.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IL-yVG2Ayc_C_drd33ZptA.png" /></figure><p>In today’s web applications, keeping information updated across multiple tabs or windows can greatly enhance the user experience. For instance, if a user logs out in one tab, you want that action to be reflected in all other tabs. The <strong>Broadcast Channel API</strong> makes this easy by allowing communication between different browsing contexts of the same origin. This article will guide you on how to use this API in a React application.</p><h3>What is the Broadcast Channel API?</h3><p>The <strong>Broadcast Channel API</strong> is a simple method to enable communication between different tabs, windows, or iframes of the same website. It allows you to broadcast messages to all other contexts listening on the same channel, making it ideal for real-time updates and synchronization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*AznCIcxWa6t5G3gX.png" /></figure><h3>Why Use It?</h3><p>• <strong>Real-Time Updates</strong>: Sync data like user sessions across different tabs.</p><p>• <strong>Ease of Integration</strong>: Simple to add to your existing React app.</p><p>• <strong>No Additional Libraries</strong>: Functions natively in modern browsers without extra dependencies.</p><h3>Setting Up the Broadcast Channel API in React</h3><p>Let’s walk through how to use the Broadcast Channel API in a React application by creating a custom hook to manage communication.</p><h3>Create a Custom Hook</h3><p>First, create a custom hook named useBroadcastChannel to encapsulate the Broadcast Channel logic.</p><pre>import { useEffect, useState } from &#39;react&#39;;<br><br>const useBroadcastChannel = (channelName) =&gt; {<br>    const [message, setMessage] = useState(null);<br>    const channel = new BroadcastChannel(channelName);<br><br>    useEffect(() =&gt; {<br>        const handleMessage = (event) =&gt; {<br>            setMessage(event.data);<br>        };<br><br>        channel.onmessage = handleMessage;<br><br>        // Clean up the channel when the component unmounts<br>        return () =&gt; {<br>            channel.close();<br>        };<br>    }, [channel]);<br><br>    const sendMessage = (msg) =&gt; {<br>        channel.postMessage(msg);<br>    };<br><br>    return { message, sendMessage };<br>};<br><br>export default useBroadcastChannel;</pre><p>This hook creates a new BroadcastChannel, listens for incoming messages, and provides a function to send messages.</p><h3>Use the Hook in a React Component</h3><p>Let’s use our custom hook in a React component to manage login sessions across different tabs.</p><pre>import React, { useEffect } from &#39;react&#39;;<br>import useBroadcastChannel from &#39;./useBroadcastChannel&#39;;<br><br>const AuthManager = () =&gt; {<br>    const { message, sendMessage } = useBroadcastChannel(&#39;auth_channel&#39;);<br>    const handleLogin = () =&gt; {<br>        // Notify all tabs that the user has logged in<br>        sendMessage({ type: &#39;login&#39;, user: &#39;JohnDoe&#39; });<br>    };<br>    const handleLogout = () =&gt; {<br>        // Notify all tabs that the user has logged out<br>        sendMessage({ type: &#39;logout&#39; });<br>    };<br>    useEffect(() =&gt; {<br>        if (message) {<br>            if (message.type === &#39;logout&#39;) {<br>                alert(&#39;You have been logged out in another tab!&#39;);<br>            }<br>        }<br>    }, [message]);<br>    return (<br>        &lt;div&gt;<br>            &lt;h1&gt;Authentication Manager&lt;/h1&gt;<br>            &lt;button onClick={handleLogin}&gt;Log In&lt;/button&gt;<br>            &lt;button onClick={handleLogout}&gt;Log Out&lt;/button&gt;<br>        &lt;/div&gt;<br>    );<br>};<br>export default AuthManager;</pre><p>This AuthManager component uses the useBroadcastChannel hook to handle user authentication state across tabs. When a user logs in or out, a message is sent to all other tabs on the auth_channel channel. If a logout message is received in any tab, it triggers an alert to notify the user.</p><h3>Conclusion</h3><p>The Broadcast Channel API provides a straightforward way to synchronize data across multiple tabs or windows in your web applications. By using a custom React hook, you can easily manage real-time messaging and improve user experience. Whether you’re handling login states or syncing other types of data, the Broadcast Channel API simplifies cross-tab communication.</p><h3>Further Reading</h3><p>• <a href="https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API">MDN Web Docs on Broadcast Channel API</a></p><h3>Connect with me</h3><ul><li><a href="https://www.linkedin.com/in/sachin-chaurasiya">LinkedIn</a></li><li><a href="https://twitter.com/sachindotcom">Twitter</a></li><li><a href="https://github.com/Sachin-chaurasiya">GitHub</a></li></ul><p><em>Originally published at </em><a href="https://peerlist.io/sachin87/articles/how-to-use-broadcast-channel-api-in-react."><em>https://peerlist.io/sachin87/articles/how-to-use-broadcast-channel-api-in-react.</em></a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc19c7a7c358" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-use-broadcast-channel-api-in-react-bc19c7a7c358">How to Use Broadcast Channel API in React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a SQL Expert Bot: A Step-by-Step Guide with Vercel AI SDK and OpenAI API]]></title>
            <link>https://medium.com/stackanatomy/building-a-sql-expert-bot-a-step-by-step-guide-with-vercel-ai-sdk-and-openai-api-77e581ce472a?source=rss-74fad1116d0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/77e581ce472a</guid>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Sachin Chaurasiya]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 03:38:18 GMT</pubDate>
            <atom:updated>2024-06-17T09:13:24.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JwaECr1lFyglsmbt" /></figure><p>OpenAI has brought the revolution in the AI field by creating the ChatGPT and now we can say the actual AI era has started and everyone from individuals to businesses using AI.</p><p>OpenAI has even created an API to build custom AI solutions like chatbots, assistants, and more. We can access the APIs using SDKs provided by OpenAI for different programming languages. There are also wrappers built on top of the API to help you build the interface easily.</p><p>Vercel has built an AI SDK for constructing the streaming user interface with TypeScript and JavaScript. The best part is that it is open-source and has support for Vercel Edge runtime.</p><p>In this article, we will build a SQL Expert ChatBot using the OpenAI API and Vercel AI SDK. We will discuss streaming responses, custom prompts, and much more.</p><h3>Setup OpenAI Account</h3><p>First, we will need to create an account on OpenAI and get an API key. You can sign up for a free account on OpenAI’s website. Once you’re logged in, go to the API keys section in the menu on the left side of the screen. From there, you can create a new API key. I have created one and named it vercel-ai-sdk, but you can choose any name you like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uUsxZBlqdmZXLL7M" /></figure><p>Okay, now that we have the OpenAI API key, let’s move on to the next section where we will talk about the Vercel AI SDK and how to set it up on your computer.</p><h3>Setup Vercel AI SDK</h3><p>The <a href="https://sdk.vercel.ai/docs">Vercel AI SDK</a> is built for OpenAI APIs and includes a range of tools for utilizing OpenAI APIs.</p><p>To begin, let’s create a Next.js application and install the dependencies ai for the Vercel AI SDK and openai for the OpenAI API client.</p><pre>pnpm dlx create-next-app ai-sql-expert <br>cd ai-sql-expert <br>pnpm install ai openai</pre><p>Make sure to have the same configuration as shown in the image below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7FrUXvEZLaBzLW4j" /></figure><p>Create a .env file in your project root and add your OpenAI API Key</p><pre>OPENAI_API_KEY=xxxxxxxxx</pre><p>Great, now that we have set up the OpenAI and Vercel AI SDKs, let’s proceed to create API routes and a user interface for our SQL Expert Bot.</p><h3>Create API Routes</h3><p>We will set up an API route to manage user message requests. When a user sends a message, the OpenAI API will process it and send a response back to Next.js.</p><p>Create a file named route.ts inside the api/chat folder in your project&#39;s src/app directory. Then, add the following code snippet</p><pre># app/api/chat/route.ts<br><br>import OpenAI from &#39;openai&#39;;<br>import { OpenAIStream, StreamingTextResponse } from &#39;ai&#39;;<br><br>const openai = new OpenAI({<br>  apiKey: process.env.OPENAI_API_KEY,<br>});<br><br>export const runtime = &#39;edge&#39;;<br><br>export async function POST(req: Request) {<br>  const { messages } = await req.json();<br><br>  const response = await openai.chat.completions.create({<br>    model: &#39;gpt-3.5-turbo&#39;,<br>    stream: true,<br>    messages,<br>  });<br><br>  const stream = OpenAIStream(response);<br>  return new StreamingTextResponse(stream);<br>}</pre><p>This section is for setting up the OpenAI instance by providing the API key.</p><pre>const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, });</pre><p>By adding this line, we are instructing Next.js to utilize edge runtime for processing the API requests.</p><pre>export const runtime = &#39;edge&#39;;</pre><p>The POST function extracts the messages field from the JSON payload sent in the request.</p><p>It then uses the openai.chat.completions.create method to send these messages to OpenAI&#39;s GPT-3.5-turbo model for processing. This method creates completions (responses) based on the provided messages.</p><p>The stream parameter is set to true, indicating that the responses should be streamed back to the client in real time.</p><p>After receiving the response from OpenAI, the code converts it into a friendly text stream using a function called OpenAIStream.</p><p>Finally, the function constructs a response using the StreamingTextResponse class and returns it. This response contains the streamed text generated by OpenAI in response to the user&#39;s messages.</p><pre>export async function POST(req: Request) {<br>  const { messages } = await req.json();<br><br>  const response = await openai.chat.completions.create({<br>    model: &#39;gpt-3.5-turbo&#39;,<br>    stream: true,<br>    messages,<br>  });<br><br>  const stream = OpenAIStream(response);<br>  return new StreamingTextResponse(stream);<br>}</pre><p>Okay, we have created the API route to handle user requests and process messages with the OpenAI API. Next, we will move on to creating the user interface for our SQL Expert Bot.</p><h3>Create The User Interface</h3><p>Before adding code for the user interface we will add the contants for initial chat messages which we will be using as custom prompt for our bot to set it’s behaviour.</p><p>Create constant/chat.constants.ts in the project&#39;s src/app directory. Then, add the following code snippet</p><pre>import { Message } from &#39;ai/react&#39;;<br><br>export const INITIAL_MESSAGES: Message[] = [<br>  {<br>    id: &#39;&#39;,<br>    role: &#39;system&#39;,<br>    content: `You are an SQL expert. you can write generate SQL queries for any given problem statement.<br>        Make sure to return the query with proper formatting and indentation.<br>        Make sure to return the query with proper explanation and comments.<br>        If you are not able to solve the problem, you can ask for more details.<br>        If user is not able to understand the query, you can explain the query in simple words.<br>        If user is providing wrong prompt, you can ask for correct prompt.<br>        `,<br>  },<br>];</pre><p>We are providing instructions to the system on how to behave in various scenarios, determining the appropriate responses, and specifying how these responses should be delivered.</p><p>Next, add the following code snippet in src/app/pages.tsx.</p><pre>&#39;use client&#39;;<br><br>import { useChat } from &#39;ai/react&#39;;<br>import Markdown from &#39;react-markdown&#39;;<br>import { INITIAL_MESSAGES } from &#39;./constant/chat.constants&#39;;<br><br>export default function Chat() {<br>  const { messages, input, handleInputChange, handleSubmit } = useChat({<br>    initialMessages: INITIAL_MESSAGES,<br>  });<br>  return (<br>    &lt;div&gt;<br>      &lt;div className=&quot;text-center py-8&quot;&gt;<br>        &lt;h2 className=&quot;text-center text-2xl font-bold mb-2&quot;&gt;SQL Expert&lt;/h2&gt;<br>        &lt;p&gt;<br>          Welcome to the SQL Expert. You can ask any SQL related questions and<br>          expert will help you out.<br>        &lt;/p&gt;<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;flex flex-col w-full max-w-2xl pb-24 mx-auto stretch gap-4&quot;&gt;<br>        {messages<br>          .filter((m) =&gt; m.role !== &#39;system&#39;)<br>          .map((m) =&gt; (<br>            &lt;div<br>              key={m.id}<br>              className=&quot;bg-gray-100 p-4 rounded flex gap-2 flex-col&quot;<br>            &gt;<br>              &lt;span className=&quot;font-medium&quot;&gt;<br>                {m.role === &#39;user&#39; ? &#39;You&#39; : &#39;Expert&#39;}<br>              &lt;/span&gt;<br>              &lt;Markdown&gt;{m.content}&lt;/Markdown&gt;<br>            &lt;/div&gt;<br>          ))}<br><br>        &lt;form<br>          className=&quot;flex gap-4 fixed bottom-0 w-full mb-8&quot;<br>          onSubmit={handleSubmit}<br>        &gt;<br>          &lt;input<br>            autoFocus<br>            className=&quot;p-2 border border-gray-300 rounded shadow-xl outline-purple-500 focus:outline-none focus:ring-2 focus:ring-purple-500 flex-grow max-w-xl&quot;<br>            value={input}<br>            placeholder=&quot;Ask your SQL related question..&quot;<br>            onChange={handleInputChange}<br>          /&gt;<br><br>          &lt;button<br>            className=&quot;border p-2 px-4 rounded shadow-xl border-gray-300 bg-purple-500 text-white&quot;<br>            type=&quot;submit&quot;<br>          &gt;<br>            Send<br>          &lt;/button&gt;<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>We will use a client component to display messages and a form for users to send their messages.</p><pre>&#39;use client&#39;;</pre><p>Since the API will return the response with markdown content, we will utilize react-markdown to parse the markdown content.</p><pre>import Markdown from &#39;react-markdown&#39;;</pre><p>The useChat hook helps you create a chat interface for your chatbot app. It makes it simple to show messages from your AI provider, handle chat input, and update the UI when new messages come in. It accepts a bunch of options, and for our case, we are using the initialMessages option to set the system&#39;s behavior.</p><pre>import { useChat } from &#39;ai/react&#39;;<br><br>const { messages, input, handleInputChange, handleSubmit } = useChat({<br>    initialMessages: INITIAL_MESSAGES,<br>  });</pre><p>This part is for displaying the messages we receive from the API. We have set a custom prompt for the system, so we will filter it out and only show the user and expert messages.</p><pre>&lt;div className=&quot;flex flex-col w-full max-w-2xl pb-24 mx-auto stretch gap-4&quot;&gt;<br>        {messages<br>          .filter((m) =&gt; m.role !== &#39;system&#39;)<br>          .map((m) =&gt; (<br>            &lt;div<br>              key={m.id}<br>              className=&quot;bg-gray-100 p-4 rounded flex gap-2 flex-col&quot;<br>            &gt;<br>              &lt;span className=&quot;font-medium&quot;&gt;<br>                {m.role === &#39;user&#39; ? &#39;You&#39; : &#39;Expert&#39;}<br>              &lt;/span&gt;<br>              &lt;Markdown&gt;{m.content}&lt;/Markdown&gt;<br>            &lt;/div&gt;<br>          ))}<br>...<br>&lt;/div&gt;</pre><p>Finally, we have the form for users to send their messages. We are using the handleSubmit function provided by the useChat hook to listen for the form submit event.</p><p>For the input field, we are using handleInputChange and input to control the input value.</p><p>Then, we have a button for submitting the form.</p><pre>&lt;div className=&quot;flex flex-col w-full max-w-2xl pb-24 mx-auto stretch gap-4&quot;&gt;<br>        ...<br>        &lt;form<br>          className=&quot;flex gap-4 fixed bottom-0 w-full mb-8&quot;<br>          onSubmit={handleSubmit}<br>        &gt;<br>          &lt;input<br>            autoFocus<br>            className=&quot;p-2 border border-gray-300 rounded shadow-xl outline-purple-500 focus:outline-none focus:ring-2 focus:ring-purple-500 flex-grow max-w-xl&quot;<br>            value={input}<br>            placeholder=&quot;Ask your SQL related question..&quot;<br>            onChange={handleInputChange}<br>          /&gt;<br><br>          &lt;button<br>            className=&quot;border p-2 px-4 rounded shadow-xl border-gray-300 bg-purple-500 text-white&quot;<br>            type=&quot;submit&quot;<br>          &gt;<br>            Send<br>          &lt;/button&gt;<br>        &lt;/form&gt;<br>&lt;/div&gt;</pre><p>Thanks to Vercel AI SDK for providing a hook like useChat that takes care of everything from displaying messages to managing user input.</p><p>Great! We have built the user interface for our SQL Expert bot. Now, in the next section, we will start the development server and test it out.</p><h3>Test The Bot</h3><p>To start the development server, run the following command in your terminal</p><pre>pnpm run dev <br>OR <br>yarn run dev <br>OR <br>npm run dev</pre><p>Visit <a href="http://localhost:3000/">http://localhost:3000</a> in your browser to view the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QhShjTnJHK5ijX1-" /></figure><p>You can try out the bot with the provided sample prompts below</p><pre>1. &quot;Create a SQL query to find the total number of orders placed by each customer in the past year, ordered by the highest number of orders.&quot;<br><br>2. &quot;Write a SQL query to identify customers who have spent more than $1000 in total on purchases within the last 3 months.&quot;<br><br>3. &quot;Design a SQL query to calculate the average time it takes for an order to be fulfilled from the moment it&#39;s placed, considering the timestamps of order placement and fulfillment.&quot;<br><br>4. &quot;Develop a SQL query to list the products with the highest profit margin, considering both the cost price and the selling price.&quot;<br><br>5. &quot;Construct a SQL query to find the monthly revenue trend for the past year, broken down by month.&quot;<br><br>6. &quot;Create a SQL query to identify customers who have not made a purchase in the last 6 months.&quot;<br><br>7. &quot;Write a SQL query to find the top 5 categories with the highest number of products sold in the last quarter.&quot;<br><br>8. &quot;Design a SQL query to identify orders with items that are out of stock at the time of purchase.&quot;<br><br>9. &quot;Develop a SQL query to calculate the total revenue generated from repeat customers versus new customers in the last month.&quot;<br><br>10. &quot;Construct a SQL query to identify any anomalies or irregularities in order quantities compared to historical averages for each product.&quot;</pre><p>Let’s see the demo with the prompt provided below</p><pre>Imagine you&#39;re tasked with optimizing the database performance of a large e-commerce platform. Write a SQL query to identify the top 10 selling products by revenue over the past month, considering both quantity sold and unit price.</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoyeBhh5wR_M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoyeBhh5wR_M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoyeBhh5wR_M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4165b9dcd6552f7180ea653c52a5eb6f/href">https://medium.com/media/4165b9dcd6552f7180ea653c52a5eb6f/href</a></iframe><h3>Conclusion</h3><p>Awesome! Now that we have a functioning SQL Expert Bot, feel free to experiment with it and customize it to suit your requirements. That’s all for this topic. Thank you for reading! If you found this article helpful, please consider liking, commenting, and sharing it with others.</p><h3>Resources</h3><ul><li><a href="https://github.com/Sachin-chaurasiya/ai-sql-expert">SQL Expert GitHub Repository</a></li><li><a href="https://sdk.vercel.ai/docs">Vercel AI SDK Docs</a></li><li><a href="https://sdk.vercel.ai/docs/api-reference/use-chat">useChat Hook Docs</a></li></ul><h3>Connect with me 👋</h3><ul><li><a href="https://www.linkedin.com/in/sachin-chaurasiya">LinkedIn</a></li><li><a href="https://twitter.com/sachindotcom">Twitter</a></li></ul><p><em>Originally published at </em><a href="https://blog.sachinchaurasiya.dev/building-a-sql-expert-bot-a-step-by-step-guide-with-vercel-ai-sdk-and-openai-api"><em>https://blog.sachinchaurasiya.dev</em></a><em> on March 3, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77e581ce472a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stackanatomy/building-a-sql-expert-bot-a-step-by-step-guide-with-vercel-ai-sdk-and-openai-api-77e581ce472a">Building a SQL Expert Bot: A Step-by-Step Guide with Vercel AI SDK and OpenAI API</a> was originally published in <a href="https://medium.com/stackanatomy">StackAnatomy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Dynamically Adjust the Height of a Textarea in React]]></title>
            <link>https://blog.stackademic.com/how-to-dynamically-adjust-the-height-of-a-textarea-in-reactjs-97579826a4df?source=rss-74fad1116d0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/97579826a4df</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Sachin Chaurasiya]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 03:35:15 GMT</pubDate>
            <atom:updated>2023-10-27T05:00:20.554Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HM90f2bE35iPW41Q" /></figure><h3>Introduction</h3><p>Have you ever been curious about how platforms like Notion, Hashnode, and others dynamically adjust the height of their page or article titles (text areas)? If you’ve noticed, as you type content into a textarea, the height is dynamically calculated based on the content on these platforms.</p><p>I wanted to achieve the same behavior on the <a href="https://open-metadata.org/">OpenMetadata</a> Knowledge articles page. In this blog post, I will share how I tackled this challenge using a custom hook.</p><h3>Custom hook</h3><p>Custom hooks in ReactJS are reusable pieces of code that encapsulate logic and state management.</p><p>Alright, let’s move further with the useAutoSizeTextArea custom hook which will dynamically adjust the height of the textarea based on its content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/680cb7c6e072acb65e11a2c7a484dbce/href">https://medium.com/media/680cb7c6e072acb65e11a2c7a484dbce/href</a></iframe><p>It takes three parameters as input</p><ul><li>id: A string representing the unique identifier of the textarea element.</li><li>textAreaRef: A reference to the HTMLTextAreaElement that you want to resize. This can be null if the textarea is not yet rendered.</li><li>value: A string representing the content of the textarea.</li></ul><p>Inside the useLayoutEffect hook, it checks if the textAreaRef is available. If it&#39;s not, it tries to find the textarea element using the provided id by querying the document&#39;s DOM.</p><p>If a valid textarea element is found (either through textAreaRef or by querying the DOM with the provided id), it proceeds to adjust the height of the textarea to fit its content. It does this by following these steps.</p><ul><li>Initially, it sets the style.height of the textarea to 0px. This temporarily hides the textarea to avoid flickering when calculating the scroll height.</li><li>It then calculates the scrollHeight of the textarea, which represents the full content height, even if it’s not currently visible due to the height being set to 0px.</li><li>Finally, it sets style.height of the textarea to the calculated scrollHeight, effectively resizing the textarea to fit its content.</li></ul><p>The hook is set to run whenever any of the dependencies ([textAreaRef, id, value]) change. This means that if the textAreaRef, id, or value of the textarea changes, the hook will recalculate the textarea&#39;s height to ensure it fits the new content.</p><p>Now, let’s incorporate this custom hook into an example application.</p><h3>Example</h3><p>For the purpose of this example, I will be using CodeSandbox to avoid local setup and focus on the topic of this blog.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fauto-size-textarea-dkyxt9%3Ffile%3D%2Fsrc%2FApp.tsx&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fdkyxt9&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fdkyxt9%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/49f7dba37c96149481285522286e2501/href">https://medium.com/media/49f7dba37c96149481285522286e2501/href</a></iframe><p>Here we have a simple App component that renders the h2 and textarea.</p><pre>const textAreaRef = useRef&lt;HTMLTextAreaElement&gt;(null);</pre><p>This code creates a reference for the textarea element and then passes it to the textarea element at line 24.</p><pre>useAutoSizeTextArea(&quot;title-input&quot;, textAreaRef.current, value);</pre><p>The magic piece is this: using the useAutoSizeTextArea custom hook and passing the id, textarea element from the textAreaRef, and, finally, the value.</p><p>Feel free to experiment with the example to observe how it dynamically calculates the height as you modify the content. Additionally, try commenting out line number 12 to see how the textarea becomes vertically scrollable, and the height remains static.</p><h3>Conclusion</h3><p>In this blog post, I have demonstrated how I addressed the challenge of dynamically adjusting the height of a textarea element based on its content, preventing the need for vertical scrolling in the title section of the <a href="https://open-metadata.org/">OpenMetadata</a> Knowledge article page.</p><p>And that’s it for this topic. Thank you for reading.</p><p>If you found this article useful, please consider liking and sharing it with others. If you have any questions, feel free to comment, and I will do my best to respond.</p><h3>Resource 💡</h3><ul><li><a href="https://react.dev/reference/react/useLayoutEffect">Learn more about useLayoutEffect hook</a></li><li><a href="https://gist.github.com/Sachin-chaurasiya/04ef328c3db93947186766a1fd5f1223">Gist of useAutoSizeTextArea hook</a></li></ul><h3>Connect with me 👋</h3><ul><li><a href="https://www.linkedin.com/in/sachin-chaurasiya">LinkedIn</a></li><li><a href="https://twitter.com/sachindotcom">Twitter</a></li></ul><p><em>Originally published at </em><a href="https://blog.sachinchaurasiya.dev/how-to-dynamically-adjust-the-height-of-a-textarea-in-reactjs"><em>https://blog.sachinchaurasiya.dev</em></a><em>.</em></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97579826a4df" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-dynamically-adjust-the-height-of-a-textarea-in-reactjs-97579826a4df">How to Dynamically Adjust the Height of a Textarea in React</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Snippet Builder — Create stunning code snippets]]></title>
            <link>https://sachin-chaurasiya.medium.com/code-snippet-builder-create-stunning-code-snippets-806e44cc894?source=rss-74fad1116d0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/806e44cc894</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[appwrite]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Sachin Chaurasiya]]></dc:creator>
            <pubDate>Thu, 06 Jul 2023 15:06:16 GMT</pubDate>
            <atom:updated>2023-07-16T16:04:00.414Z</atom:updated>
            <content:encoded><![CDATA[<h3>Code Snippet Builder — Create stunning code snippets</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2AY3EEkJ3kytDuvetIwXcw.png" /></figure><p>The <strong>Code Snippet Builder</strong> is an innovative tool designed to help developers and programmers create visually appealing and professional-looking code snippets for various programming languages. With its user-friendly interface and drag-and-drop functionality, the builder simplifies the process of showcasing code in an attractive and customizable manner.</p><p>Whether you need to <strong>document your code</strong>, <strong>share examples in tutorials</strong>, or enhance your <strong>technical documentation</strong>, the Code Snippet Builder is the perfect solution. It offers a wide range of customizable options, including various templates and styling features, allowing you to create snippets that align with your branding or project requirements.</p><p>The builder’s intuitive <strong>drag-and-drop</strong> functionality enables you to effortlessly arrange code blocks, add syntax highlighting, and format your snippets to make them more visually engaging. You can easily customize the appearance of your code snippets, adjusting font styles, colors, background themes, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*zkCLBqRK24pdeKRm.png" /></figure><p>The Code Snippet Builder supports multiple programming languages, catering to the diverse needs of developers across different domains. Whether you’re working with Python, JavaScript, TypeScript, or any other language, you can rely on the builder to generate beautiful code snippets that effectively communicate your ideas.</p><p>Using the Code Snippet Builder, you can elevate your code documentation, making it more accessible and visually appealing to fellow developers, clients, or users. Start building beautiful code snippets today and enhance how you present and share your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*gIrpM0DFiZ_ulT7p.png" /></figure><blockquote><em>The desktop version of our website provides the best experience. For optimal usage, please access it from your desktop.</em></blockquote><h3>Tech Stack</h3><ul><li><strong>ReactJs</strong>: Empowering the creation of UI components with its component-based architecture.</li><li><strong>TypeScript</strong>: Enabling type safety and preventing runtime errors in the development process.</li><li><strong>Netlify:</strong> Facilitating the seamless deployment of the project.</li><li><strong>Appwrite Cloud</strong></li><li><strong>Auth:</strong> Streamlining authentication and authorization management.</li><li><strong>Database:</strong> Serving as a reliable storage solution for the snippets of data.</li><li><strong>Storage:</strong> Providing a secure and efficient repository for storing the snapshot images of code snippets.</li></ul><h3>Challenges We Faced</h3><p>During the development process, I encountered some exciting challenges that I had to overcome by reading documentation, collaborating with the Appwrite community, and seeking help from other developers.</p><p>These particular aspects proved to be the most difficult for me.</p><h4>Database relationship</h4><p>When working with the Appwrite cloud, I encountered a version mismatch. The version I was using, 1.1.x, didn’t have support for creating relationships between users and their data. To tackle this challenge, I reached out to the helpful Appwrite community on Discord. They provided me with valuable suggestions and feedback. Ultimately, I decided to associate the user with the snippet data by storing the user ID. This solution allowed me to overcome the limitation and establish the desired relationship between users and their data.</p><h4>Condition Query</h4><p>When I was working on listing users’ snippets on the dashboard, I came across a challenge. I needed to figure out how to fetch only the snippets belonging to the current user. After reading the documentation, I discovered a solution. Appwrite provides a Query model that allows us to write conditions, which helped me filter and fetch only the snippets associated with the current user.</p><pre>Query.equal(&quot;creator&quot;, &quot;creatorId&quot;)</pre><h4>Snippet Snapshot image</h4><p>While working on the dashboard, I encountered a challenge when I wanted to display a visual preview of the snippets created by the user. The problem was how to store the snapshot image data. To tackle this, I referred to the storage documentation and discovered that Appwrite offers a set of methods specifically designed for creating, updating, and deleting files of various types such as PNG, JPG, and more. This enabled me to successfully store and manage the snapshot images associated with the snippets.</p><h3>Public Code Repo</h3><p>The Code Snippet Builder welcomes contributions and has a <a href="https://github.com/Sachin-chaurasiya/Code-Snippets-Builder">public repository</a> available for collaboration.</p><p>Code Snippet Builder is licensed under the MIT License — see the <a href="https://github.com/Sachin-chaurasiya/Code-Snippets-Builder/blob/main/LICENSE">LICENSE</a> file for details.</p><h3>Demo Link</h3><p>Website: <a href="https://snippetbuilder.sachinchaurasiya.dev/">https://snippetbuilder.sachinchaurasiya.dev/</a></p><p>Email: <a href="https://mailto:demo@codesnippetbuilder.com/">demo@codesnippetbuilder.com</a></p><p>Password: demo@123</p><p>And that’s it for this topic. Thank you for reading.</p><h3>Connect with me 👋</h3><ul><li><a href="https://www.linkedin.com/in/sachin-chaurasiya"><strong>LinkedIn</strong></a></li><li><a href="https://twitter.com/sachindotcom"><strong>Twitter</strong></a></li></ul><p><em>Originally published at </em><a href="https://dev.to/sachinchaurasiya/code-snippet-builder-create-stunning-code-snippets-1olf"><em>https://dev.to</em></a><em> on July 6, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=806e44cc894" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Tuple Types: The What, Why, and How]]></title>
            <link>https://javascript.plainenglish.io/typescript-tuple-types-the-what-why-and-how-31b09077c7b3?source=rss-74fad1116d0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/31b09077c7b3</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sachin Chaurasiya]]></dc:creator>
            <pubDate>Mon, 29 May 2023 06:17:09 GMT</pubDate>
            <atom:updated>2023-05-29T06:17:09.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YO22r0_g0yfNoBK7" /></figure><p><strong>TypeScript</strong> is a tool that helps JavaScript developers write better code by allowing them to define rules for the types of data they want to use. By doing this, TypeScript makes it easier to ensure that the code works correctly and reduces the risk of errors.</p><p>In this article, we’re going to explore the concept of tuple types in TypeScript, which is just one of the many data types that TypeScript supports. We’ll cover what tuple types are, why they’re useful, and provide some examples to help you understand how to use them.</p><h3>What are tuple types? 🤔</h3><p>In TypeScript, a tuple is a finite ordered list of elements that can have different data types. Tuples are similar to arrays in that they can store multiple values, but unlike arrays, tuples have a fixed length and their elements can have different data types.</p><p>To demonstrate a tuple type in TypeScript, let’s consider a simple example of an Open Source user data that includes their name and total commits.</p><pre>const user: [string, number] = [&#39;Sachin Chaurasiya&#39;,3099]</pre><p>Another great example of tuple types in action is in ReactJS hooks, where they’re used as a return type to represent structured data.</p><pre>// Example from react types<br>function useState&lt;S&gt;(initialState: S | (() =&gt; S)): [S, Dispatch&lt;SetStateAction&lt;S&gt;&gt;];</pre><p>In this case, the tuple type [S, Dispatch&lt;SetStateAction&lt;S&gt;&gt;] contains two elements: the first element is of type S and represents the data being stored, while the second element is a dispatch function with the same type as the first element, which is used to update the stored data.</p><h3>Why tuple types are useful? 🤔</h3><p>Tuple types can be useful for a few reasons,</p><ul><li>Tuple types allow you to represent a collection of values that have a specific order and data type.</li><li>Tuple types can be used to return multiple values from a function without having to create a custom object or array.</li><li>Tuple types make it easier to ensure that the data you’re working with is structured correctly.</li></ul><p>Now that we’ve covered what tuple types are and why they’re beneficial, let’s dive into some examples to understand their usage better.</p><h3>Usage ✨</h3><p>Suppose we want to store a user’s Open Source contributions data, including their name and the number of commits they’ve made. In this scenario, using tuple types would be an appropriate solution.</p><pre>type UserContribution = [string, number];<br><br>const getUserContribution = (user: User): UserContribution =&gt; {<br>  const name = `${user.firstName} ${user.lastName}`;<br>  const totalCommits = fetchCommits(user.userName);<br><br>  return [name, totalCommits];<br>};</pre><p>In this scenario, we are using the UserContribution tuple type as the return type of the getUserContribution function to ensure that we receive structured data.</p><h3>Accessing the tuple-type data</h3><p>Accessing data in a tuple type is similar to accessing elements in an array, using indexes. However, with tuples, we have a fixed length and know exactly what type of data is stored at each index.</p><pre>const userData: User = {<br>  firstName: &quot;Sachin&quot;,<br>  lastName: &quot;Chaurasiya&quot;,<br>  userName: &quot;Sachin-chaurasiya&quot;,<br>};<br><br>const userContribution = getUserContribution(userData);<br><br>console.log(userContribution[0]); // Sachin Chaurasiya<br>console.log(userContribution[1]); // 3099</pre><blockquote><em>What happens if we try to access an index that is outside the bounds of the tuple?</em></blockquote><p>if we try to access an index that is outside the bounds of the tuple then TypeScript will throw an error.</p><pre>console.log(userContribution[2]) <br><br>// Tuple type &#39;UserContribution&#39; of length &#39;2&#39; has no element at index &#39;2&#39;.</pre><h3>Destructuring the tuple-type data</h3><p>To avoid issues with out-of-bounds indexes, we can use JavaScript destructuring like the following.</p><pre>const [user, totalCommits] = getUserContribution(userData);</pre><h3>Readonly tuple types</h3><p>In certain scenarios, we may not want certain pieces of data to be modified. In these cases, we can use readonly tuple types.</p><p>In our scenario, we don’t want anyone to modify the userContribution data after it has been defined, so we can modify the UserContribution tuple type to be readonly.</p><pre>type UserContribution = readonly [string, number]</pre><p>So if we try to modify the data in a tuple type, TypeScript will throw an error.</p><pre>const contributionData = getUserContribution(userData);<br>contributionData[1] = 4000<br><br>// Cannot assign to &#39;1&#39; because it is a read-only property.</pre><h3>Summary 💡</h3><p>In This article, we covered the basics of tuple types in TypeScript, including their definition, benefits, and practical applications. We also explored an example of how ReactJS hooks utilize tuple types as a return type. By understanding tuple types, you can make your code more organized, readable, and easier to maintain.</p><p>That concludes this topic. Thank you for reading!</p><p>If you found this article helpful, please consider liking and sharing it with others. If you have any questions, feel free to leave a comment and I will do my best to provide a helpful response.</p><h3>Resource 📝</h3><ul><li><a href="https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types">Official TypeScript Documentation for tuple types</a></li><li><a href="https://www.typescripttutorial.net/typescript-tutorial/typescript-tuple/">TypeScript tutorial tuple type guide</a></li></ul><h3>Connect with me 👋</h3><ul><li><a href="https://www.linkedin.com/in/sachin-chaurasiya">LinkedIn</a></li><li><a href="https://twitter.com/sachindotcom">Twitter</a></li></ul><p><em>Originally published at </em><a href="https://blogs.deuexsolutions.com/typescript-tuple-types-the-what-why-and-how"><em>https://blogs.deuexsolutions.com</em></a><em>.</em></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31b09077c7b3" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/typescript-tuple-types-the-what-why-and-how-31b09077c7b3">TypeScript Tuple Types: The What, Why, and How</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Test Custom Hook in React]]></title>
            <link>https://javascript.plainenglish.io/how-to-test-custom-hook-in-react-4c045e225871?source=rss-74fad1116d0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c045e225871</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sachin Chaurasiya]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 06:17:30 GMT</pubDate>
            <atom:updated>2023-04-26T06:17:30.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s7t_WkKDjb1uebR1" /></figure><h3>What is a custom hook? 🤔</h3><p>Custom hooks in ReactJS are reusable pieces of code that encapsulate logic and state management. As developers, we need to ensure that these hooks work as intended and do not have any unintended side effects. This is where testing custom hooks becomes crucial.</p><p>In this article, we will explore how to test custom hooks in ReactJS using the useClipboard hook as an example.</p><h3>What is the useClipboard hook? 🤔</h3><p>The useClipboard the hook is a simple hook that allows you to copy text to the clipboard. It takes three parameters: the <strong>text to copy</strong>, the <strong>delay (in ms)</strong> to switch back to the initial state once copied, and a <strong>callback function</strong> to execute when the content is copied to the clipboard.</p><p>You can read more about how it uses the clipboard API to copy the text <a href="https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API">here</a>.</p><pre>import { useCallback, useEffect, useState } from &#39;react&#39;;<br><br>const useClipboard = (<br>  value: string,<br>  timeout = 1500,<br>  callBack?: () =&gt; void<br>) =&gt; {<br>  const [hasCopied, setHasCopied] = useState(false);<br>  const [valueState, setValueState] = useState(value);<br><br>  const handleCopy = useCallback(async () =&gt; {<br>    try {<br>      await navigator.clipboard.writeText(valueState);<br>      setHasCopied(true);<br>      callBack &amp;&amp; callBack();<br>    } catch (error) {<br>      setHasCopied(false);<br>    }<br>  }, [valueState]);<br><br>  useEffect(() =&gt; setValueState(value), [value]);<br><br>  useEffect(() =&gt; {<br>    let timeoutId: number | null = null;<br><br>    if (hasCopied) {<br>      timeoutId = Number(<br>        setTimeout(() =&gt; {<br>          setHasCopied(false);<br>        }, timeout)<br>      );<br>    }<br><br>    return () =&gt; {<br>      if (timeoutId) {<br>        clearTimeout(timeoutId);<br>      }<br>    };<br>  }, [timeout, hasCopied]);<br><br>  return {<br>    onCopyToClipBoard: handleCopy,<br>    hasCopied,<br>  };<br>};</pre><h3>Test the useClipboard hook 🧪</h3><p>We first need to create a test file to begin testing the hook. Let’s call it useClipboard.test.tsx. In this file, we&#39;ll import the useClipboard hook and any necessary dependencies.</p><pre>import { renderHook, act } from &#39;@testing-library/react-hooks&#39;;<br>import { useClipboard } from &#39;./useClipboard&#39;;</pre><h3>What is renderHook ? 💡</h3><p>renderHook is a function provided by the @testing-library/react-hooks library that allows you to test React hooks in isolation.</p><ul><li>It provides a testing environment for React hooks by rendering them in a mock component.</li><li>It allows you to test the hook’s behavior and state changes in isolation without needing a full React component.</li><li>It returns an object with a result property that holds the current state of the hook.</li></ul><p>Alright, now we know what is renderHook function and how it works.</p><p>Next, we’ll write our first test to check if the hook returns an object with two properties: onCopyToClipBoard and hasCopied.</p><h3>Should return an object with two properties 🧪</h3><pre>it(&#39;should return an object with onCopyToClipBoard and hasCopied properties&#39;, () =&gt; {<br>  const { result } = renderHook(() =&gt; useClipboard(&#39;test&#39;));<br>  expect(result.current).toHaveProperty(&#39;onCopyToClipBoard&#39;);<br>  expect(result.current).toHaveProperty(&#39;hasCopied&#39;);<br>});</pre><p>In this test, we render the hook using the renderHook function from @testing-library/react-hooks. We pass in the text we want to copy as the first argument. Then we use the expect function to check if the hook returns an object with the two properties we expect.</p><p>Next, we’ll write a test to check if the onCopyToClipBoard function updates the hasCopied state.</p><pre>it(&#39;should update hasCopied state when content is copied to clipboard&#39;, async () =&gt; {<br>  const { result } = renderHook(() =&gt; useClipboard(&#39;test&#39;));<br>  await act(async () =&gt; {<br>    result.current.onCopyToClipBoard();<br>  });<br>  expect(result.current.hasCopied).toBe(true);<br>});</pre><p>In this test, we call the onCopyToClipBoard function and use the await keyword to wait for the function to finish executing. We then check if the hasCopied state is set to true.</p><p>Finally, we’ll write a test to check if the hasCopied state resets after the timeout.</p><h3>Should reset the state after a timeout 🧪</h3><pre>it(&#39;should reset hasCopied state after timeout&#39;, async () =&gt; {<br>  jest.useFakeTimers();<br>  const { result, rerender } = renderHook(() =&gt;<br>    useClipboard(&#39;test&#39;, 1500)<br>  );<br>  await act(async () =&gt; {<br>    result.current.onCopyToClipBoard();<br>  });<br>  expect(result.current.hasCopied).toBe(true);<br>  act(() =&gt; {<br>    jest.advanceTimersByTime(1500);<br>  });<br>  rerender();<br>  expect(result.current.hasCopied).toBe(false);<br>  jest.useRealTimers();<br>});</pre><p>In this test, we use the jest.useFakeTimers() function to fake the timer. We render the hook with a delay of 1500ms and call the onCopyToClipBoard function. We then advance the timer by 1500ms and rerender the hook. Finally, we check if the hasCopied state is set to false.</p><h3>Conclusion ✨</h3><p>Testing custom hooks in ReactJS is crucial for ensuring the functionality of our components. While it may be challenging at times, with the right approach and tools like @testing-library/react-hooks, we can write effective tests and ensure our hooks work as intended.</p><p>And that’s it for this topic. Thank you for reading.</p><p>If you found this article useful, please consider liking and sharing it with others. If you have any questions, feel free to comment, and I will do my best to respond.</p><h3>Resource 💡</h3><ul><li><a href="https://testing-library.com/docs/react-testing-library/api/#renderhook">Learn more about render hook</a></li><li><a href="https://gist.github.com/Sachin-chaurasiya/56154e66a68f077bc1d858ca4d3c92da">Gist of useClipboard hook</a></li></ul><h3>Connect with me 👋</h3><ul><li><a href="https://www.linkedin.com/in/sachin-chaurasiya">LinkedIn</a></li><li><a href="https://twitter.com/sachindotcom">Twitter</a></li></ul><p><em>Originally published at </em><a href="https://blogs.deuexsolutions.com/how-to-test-custom-hook-in-reactjs"><em>https://blogs.deuexsolutions.com</em></a><em>.</em></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c045e225871" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-test-custom-hook-in-react-4c045e225871">How to Test Custom Hook in React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>