<?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 Judy@webdecoded on Medium]]></title>
        <description><![CDATA[Stories by Judy@webdecoded on Medium]]></description>
        <link>https://medium.com/@judy-webdecoded?source=rss-17b9f0fce28f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JZ-el6VIkFRBH43lUSwH4g.png</url>
            <title>Stories by Judy@webdecoded on Medium</title>
            <link>https://medium.com/@judy-webdecoded?source=rss-17b9f0fce28f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:33:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@judy-webdecoded/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[How I Integrated Headless CMS in my NextJS App]]></title>
            <link>https://judy-webdecoded.medium.com/how-i-integrated-headless-cms-in-my-nextjs-app-68899ccb1b04?source=rss-17b9f0fce28f------2</link>
            <guid isPermaLink="false">https://medium.com/p/68899ccb1b04</guid>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[headless-cms]]></category>
            <dc:creator><![CDATA[Judy@webdecoded]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 23:06:54 GMT</pubDate>
            <atom:updated>2025-01-08T23:06:54.878Z</atom:updated>
            <content:encoded><![CDATA[<p>While building my portfolio website, I decided to include a blog section. Since I already had an existing Next.js app, I wanted the blog functionality to be integrated within it rather than using a separate platform. This is somewhat ironic since you’re reading this on Medium, but I plan to explore SEO opportunities for my self-hosted blog:)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgmav8mT7QVlDnAeEuAO1Q.png" /></figure><p>For the headless CMS, I chose <a href="https://payloadcms.com/">Payload CMS</a> because it’s open-source and offers all the features I needed.</p><h3>Step 1: Installing Dependencies</h3><pre>npm i payload @payloadcms/next @payloadcms/richtext-lexical sharp graphql --legacy-peer-deps</pre><p>This is the list of packages you’d need to run the Payload in your application, and you can install them with other package managers like pnpm.</p><h3>Step 2: Picking a Database</h3><p>Next, we need to install a database adapter package. I chose Postgres as my database, which requires this installation command:</p><pre>npm i @payloadcms/db-postgres --legacy-peer-deps</pre><p>If you already have a hosted database, you can use its URI to connect to Payload. If not, you can easily create and host one on <a href="https://vercel.com/">Vercel</a>. From the dashboard, add a new store:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*FJQmvf9IvwYXm86zV4k09Q.png" /><figcaption>Vercel Dashboard</figcaption></figure><p>The system will generate a Database URI in different formats. Select the psql tab and copy the value in quotes, which begins with &quot;postgres://…&quot;</p><p>After copying this value, I created an .env file in my repository’s root directory with the following variables:</p><pre>DATABASE_URI=&quot;postgres://....&quot; // &lt;- paste your database URI here<br>PAYLOAD_SECRET=&quot;&quot;</pre><p>For PAYLOAD_SECRET , I generated it using a command that I ran in my terminal:</p><pre>openssl rand -base64 32</pre><p>This command outputs the value that can be pasted in the .env file.</p><h3>Step 3: Organizing Files</h3><p>It’s best to separate app’s other logic from that of payload and this is proposed structure from payload templates:</p><pre>app/<br>├─ (payload)/<br>├── // Payload files<br>├─ (app)/<br>├── // Your app files</pre><p>So for this step, I moved all the files I had in /app folder in the newly created folder /(landing-page) . You can name the folder containing non-CMS related logic anything you want — since it’s placed inside parentheses, it won’t appear in your routes.<br>As for the (payload) folder, I copied the files from <a href="https://github.com/payloadcms/payload/tree/main/templates/blank/src/app/(payload)">Payload Blank Template</a> while converting them to JavaScript as I am not using TypeScript in the portfolio project.</p><h3>Step 4: Updating NextJS Config</h3><p>For configuration, I modified the root next.config.mjs file to incorporate the Payload plugin:</p><pre>import { withPayload } from &quot;@payloadcms/next/withPayload&quot;;<br>/** @type {import(&#39;next&#39;).NextConfig} */<br>const nextConfig = {<br>  // Your Next.js config here<br>  experimental: {<br>    reactCompiler: false,<br>  },<br>};<br>// Make sure you wrap your `nextConfig`<br>// with the `withPayload` plugin<br>export default withPayload(nextConfig);</pre><p>If yours doesn’t have a .mjs file extension that you can add</p><p>“type”: “module” to your package.json</p><h3>Step 5: Creating Payload Config</h3><p>Collections provide a way to organize CMS data. I created a separate folder for collections in my app directory and added a new file to define the Posts collection:</p><pre>// /app/collections/Posts.js<br>export const Posts = {<br>  slug: &quot;posts&quot;,<br>  fields: [<br>    {<br>      name: &quot;title&quot;,<br>      type: &quot;text&quot;,<br>      required: true,<br>    },<br>    {<br>      name: &quot;content&quot;,<br>      type: &quot;richText&quot;,<br>    },<br>    {<br>      name: &quot;includedInBlog&quot;,<br>      type: &quot;checkbox&quot;,<br>      defaultValue: true,<br>    },<br>  ],<br>};</pre><p>In the root of my project, I created a new file payload.config.js and added configurations that set up the rich text editor, use my environment variables, and create a Posts Collection — the data type I’ll use to store my blog posts.</p><pre>import sharp from &quot;sharp&quot;;<br>import { lexicalEditor } from &quot;@payloadcms/richtext-lexical&quot;;<br>import { postgresAdapter } from &quot;@payloadcms/db-postgres&quot;;<br>import { buildConfig } from &quot;payload&quot;;<br>import { Posts } from &quot;./src/app/collections/Posts&quot;; // or ./app/collections/Posts if you are not using `src` folder<br>export default buildConfig({<br>  // If you&#39;d like to use Rich Text, pass your editor here<br>  editor: lexicalEditor(),<br>  // Define and configure your collections in this array<br>  collections: [Posts],<br>  // Your Payload secret - should be a complex and secure string, unguessable<br>  secret: process.env.PAYLOAD_SECRET || &quot;&quot;,<br>  // Whichever Database Adapter you&#39;re using should go here<br>  // Mongoose is shown as an example, but you can also use Postgres<br>  db: postgresAdapter({<br>    pool: {<br>      connectionString: process.env.DATABASE_URI || &quot;&quot;,<br>    },<br>  }),<br>  // If you want to resize images, crop, set focal point, etc.<br>  // make sure to install it and pass it to the config.<br>  // This is optional - if you don&#39;t need to do these things,<br>  // you don&#39;t need it!<br>  sharp,<br>});</pre><p>and modified my jsonconfig.json file to include payload configuration:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;paths&quot;: {<br>      &quot;@/*&quot;: [&quot;./src/*&quot;],<br>      &quot;@payload-config&quot;: [<br>        &quot;./payload.config.js&quot;<br>      ]<br>    }<br>  }<br>}</pre><h3>Step 6: Login</h3><p>At this stage, I can create a new user by navigating to <a href="http://localhost:3000/admin">http://localhost:3000/admin</a> and start creating Posts!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rguon2zfV0f1-9RNWH0ahQ.png" /><figcaption>Admin Dashboard</figcaption></figure><p>If you’d like to check out source code, here is the repository:<br><a href="https://github.com/webdecoded-tutorials/nextjs-blog-portfolio">https://github.com/webdecoded-tutorials/nextjs-blog-portfolio</a></p><p>Video tutorial(also includes building the portfolio):</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DK-hGb9W6wHc&amp;type=text%2Fhtml&amp;schema=google&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FK-hGb9W6wHc" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1675bdc84dc095742ca7b7dce951a8b/href">https://medium.com/media/e1675bdc84dc095742ca7b7dce951a8b/href</a></iframe><p>Follow me on X:</p><p><a href="https://x.com/webdecoded_g">https://x.com/webdecoded_g</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68899ccb1b04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built an AI App to Review YC Applications in a Day]]></title>
            <link>https://judy-webdecoded.medium.com/how-i-built-an-ai-app-to-review-yc-applications-in-a-day-92e2921a6f6b?source=rss-17b9f0fce28f------2</link>
            <guid isPermaLink="false">https://medium.com/p/92e2921a6f6b</guid>
            <category><![CDATA[ycombinator]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Judy@webdecoded]]></dc:creator>
            <pubDate>Fri, 30 Aug 2024 00:07:59 GMT</pubDate>
            <atom:updated>2024-08-30T00:40:19.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzPEzGHZ0ICvObmYCwnZfA.gif" /></figure><p>YCombinator is doing first ever Fall batch this year. Per their <a href="https://www.ycombinator.com/blog/yc-fall-2024">website</a>, they introduced fall batch due to high demand and because the deadline was 8/27 there were a number of people applying and looking to get a quick feedback on their applications. As someone who has personally been following YC content and a journey of their startups, I knew where to look for content when it came to finding useful tips, do’s and don’ts and things that needed to be highlighted when applying to the accelerator.</p><p>After collecting the links of it’s public data(YouTube and the ycombinator website), I created a new project on <a href="https://customgpt.ai/?fpr=webdecoded23">CustomGPT</a> and added sources that I would later use to build my custom AI agent on. Since the data is too large for a context window for most AI models it would not have worked if I passed it as a single prompt. What I could have also done to provide access to AI to the data is to scrape it and store in a vector database and then when running queries, for example “can you review this section about equity?” it would do a smart search on the database find the knowledge related to the equity and return an answer based on the allocated information. If you want to build vector databases this way check out <a href="https://youtu.be/92QqWVB6GNg?si=YRw5xtOMgCxnktqy">my tutorial</a>. Although this part would have taken extra steps since with the video content would need to generate transcriptions first and than create embeddings to store in the database and because with CustomGPT I could skip these steps I went with it.</p><p>After adding YCombinator’s website as a source to the project, I noticed it scraped some general information pages but missed the profiles of companies from YC’s previous batches. These profiles contain valuable information — they showcase how companies describe their businesses, emphasize key points, and present their competitive advantages. Such insights are crucial for an AI assistant tasked with reviewing applications.</p><p>This meant I had to scrape the data myself, so I fired up a <a href="https://colab.research.google.com/">Google Jupyter notebook</a> to write the logic for gathering the data, creating a file, and storing it in Drive. From there, I could later download and add it to my project in CustomGPT.</p><p>The first step in the notebook was installing the necessary packages.</p><p>After this, I wrote a function to generate an array of company links from the Startup Directory page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qe5KXhPyw576go6fQdDo8Q.png" /><figcaption>YC Startup Directory</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJb1plSRT-mzIOlgIHJZWQ.png" /></figure><p>I ran the function but noticed that it only returned the links from the header not the company section 🤔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AosOmhtpo13kNgUxJw7cqA.png" /></figure><p>I realized that upon the initial page load, only some HTML containing the header was available. The data related to companies was likely being loaded from the server asynchronously. To address this, I had to update the function to wait until that data became available. Additionally, since I didn’t want to load every link on the page, I inspected the companies section in my browser and specifically targeted that part of the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgOj1LoznmTR5Mb0LThlFw.png" /></figure><p>Now we have an array of the links we want to get data from!</p><p>Next things we need is a function that will scrape them so we will use it to loop over the items in the array and write it’s contents to a file in drive. Here’s the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F93-sc0dL_j5s5EnaHzKUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nr1Kwcdnjgs9hPBdpBXkNQ.png" /></figure><p>crawled_content.txtbecame one large text file. I initially wondered if I needed to format it before passing it to the AI. However, once I added it to CustomGPT and asked a few questions in their chat, it turned out that the AI had developed a pretty good understanding of the text without additional formatting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXn70R7mOWGjYJK-91h92A.png" /></figure><p>Inside the Chatbot Persona of the settings, I added the initial instructions to define what the role of the agent is: You are a custom chatbot assistant that is responsible for reviewing startup applications for YCombinator and helping founders update their applications and give suggestions on things and wording they have to change.</p><p>This would be equivalent of passing the first prompt before sending the rest of the messages to the chat:</p><pre>const completion = await openai.chat.completions.create({<br>    messages: [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a custom chatbot assistant that is responsible for reviewing startup applications for YCombinator and helping founders update their applications and give suggestions on things and wording they have to change.&quot;},<br>      ],<br>    model: &quot;gpt-4o-mini&quot;,<br>  });</pre><p>Now it’s time to build the UI that will utilize the <a href="https://docs.customgpt.ai/reference/post_api-v1-projects-projectid-conversations-sessionid-messages">CustomGPT API</a> endpoints: “create a message” and “send a message.” For this part, I generated API keys and set up a NextJS project. I initially wondered if NextJS might be overkill — perhaps I should have just created a React app with Vite, given that I only needed a simple form. However, to securely interact with the API, I needed NextJS Routes.</p><p>Every time a user submits their application information for review, I create a new conversation. The details aren’t stored anywhere — they’re simply sent to the AI to fetch a response.</p><p>After creating a conversation, I send requests to the “send a message” API to get suggestions on specific parts of the application. These requests include both the question from the form and the user’s answer. I selected questions from YC’s application form, but I didn’t include all sections since some contain personal information.</p><p>For form components like Input and Card, I used shadcn to minimize styling efforts. I installed the components and adjusted the Tailwind configuration to match YC’s color palette. To achieve this, I pasted YC’s main hex color into the <a href="https://zippystarter.com/tools/shadcn-ui-theme-generator">ZippyStarter</a>. This generated configurations which I then added to my globals.css file. I only needed to tweak the background color slightly, as the theme generator’s shade differed from what I wanted.</p><p>And this is the end result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BOL6iMpfAkYMqgyXvX2TLw.png" /><figcaption>yc-interview-ai.vercel.app</figcaption></figure><p>If you found this walkthrough on building a custom AI agent for YC application reviews helpful, I’d appreciate a <a href="https://x.com/webdecoded_g/status/1828837243978428606">retweet</a>!</p><p>Want to stay in the loop on more AI tools and tutorials? Subscribe to my <a href="https://www.youtube.com/@webdecoded/videos">YouTube channel</a>, where I share courses on building full-stack projects.</p><p>Thanks for reading, and best of luck with your YC applications!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92e2921a6f6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create OpenAI Embeddings & Why You Need to Know About Them]]></title>
            <link>https://judy-webdecoded.medium.com/how-to-create-openai-embeddings-why-you-need-to-know-about-them-30f9107c1084?source=rss-17b9f0fce28f------2</link>
            <guid isPermaLink="false">https://medium.com/p/30f9107c1084</guid>
            <category><![CDATA[text-embedding]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Judy@webdecoded]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 21:50:19 GMT</pubDate>
            <atom:updated>2024-03-12T21:50:19.536Z</atom:updated>
            <content:encoded><![CDATA[<p>Text embeddings are a NLP technique that converts textual data into numerical vectors that can be processed by machine learning algorithms, especially large models. These vector representations are designed to capture the semantic meaning and context of the words they represent.</p><p>The technique involves taking a chunk of text and turning it into a vector. The output looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IW0OsoaecJxh1BLtgod5WA.png" /><figcaption>Text Embeddings</figcaption></figure><p>The output represents a point in high-dimensional space, think Cartesian Coordinate System but instead of having 2 dimensions(x- and y-axis) there’s thousands of them. The words that are also closer to each other in terms of semantic meaning would be placed closer to each other.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhpDEy7K7vgunx9O56WCIA.png" /></figure><p>One of the best uses for embeddings are semantic search, where it returns not the exact match for words but instead the best results in terms of semantic meaning.</p><p>Using OpenAI’s GPT is one of the ways of generating embeddings, you can use other models like BERT.</p><p>To get started you would need an API key from OpenAI, create an account if you don’t already have one and navigate to this <a href="https://platform.openai.com/api-keys">link</a> inside your dashboard where you can click create a new key.</p><p>We will install <a href="https://www.langchain.com/">Langchain</a>, that’s a framework for building LLM-based applications I have found it helpful to streamline lot of AI-related functionalities and tasks when building apps.</p><p>Inside your project you can run the command:</p><p>npm install langchain @langchain/openai</p><p>And create a new function:</p><pre>import { OpenAIEmbeddings } from &quot;@langchain/openai&quot;;</pre><pre>const generateEmbeddings = async (text) =&gt; {<br>	  const embeddings = new OpenAIEmbeddings({<br>          openAIApiKey: &quot;&quot;, // pass your api key here<br>          modelName: &quot;text-embedding-3-large&quot;,<br>  });<br>  <br>  const vectors = await embeddings.embedDocuments([text]);<br>  return vectors;<br>}</pre><p>The functions will generate embeddings that you can use for search, summarization or with your vector database. And you can call the function by doing:</p><pre>const text = &quot;Your text here&quot;;<br>generateEmbeddings(text).then(vectors =&gt; {<br>  // do stuff here<br>  console.log(vectors); // examine results<br>});</pre><p>If you prefer a video format, where I also create a Vector Database and build a document Summarization Tool, you can check out the following:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F92QqWVB6GNg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D92QqWVB6GNg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F92QqWVB6GNg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/849eaa8175e0c0424e23992fc536da2f/href">https://medium.com/media/849eaa8175e0c0424e23992fc536da2f/href</a></iframe><p>Looking to build a complete AI Saas Application with subscriptions? Check out AI Form Builder:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzzWypOl4JkY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzzWypOl4JkY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzzWypOl4JkY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dda4102ab74bd5d8143cd638fb8ca69/href">https://medium.com/media/9dda4102ab74bd5d8143cd638fb8ca69/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30f9107c1084" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Integrated Authentication Next-Auth V5 in my NextJS 14 Application]]></title>
            <link>https://judy-webdecoded.medium.com/how-i-integrated-authentication-next-auth-v5-in-my-nextjs-14-application-0d57f84cf4ac?source=rss-17b9f0fce28f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d57f84cf4ac</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextauth]]></category>
            <dc:creator><![CDATA[Judy@webdecoded]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 06:49:10 GMT</pubDate>
            <atom:updated>2024-02-14T17:03:57.917Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Integrate Authentication in a Next.js Project</h3><p>This comprehensive guide will walk you through the process of integrating Next Auth v5 into a Next.js project. If you prefer a video walk-through, there is also one on my channel:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqDRQ2EaWsNM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqDRQ2EaWsNM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqDRQ2EaWsNM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cef16ed7269b1238d5cd22454cb7551b/href">https://medium.com/media/cef16ed7269b1238d5cd22454cb7551b/href</a></iframe><p>I recently integrated the new version of next-auth, which is V5. The installation took longer than I expected due to the lack of documentation. Since next-auth is becoming part of auth.js, original website does contain more detailed documentation for previous versions, but the new version documentation is still in progress to be migrated to the new website. Let’s dive into all the steps I took to set it up and also explore how to use session information and auth functions both in server and client components!</p><h3>Step 1: Set up your Next.js project</h3><p>First, you need a Next.js project to work with. If you don’t have one yet, you can create it using the create-next-app command in your terminal. This command will set up a new project with all the necessary files and dependencies for a Next.js application.</p><pre>npx create-next-app@latest</pre><h3>Step 2: Install Next Auth</h3><p>The next step is to install the Next Auth module. You can do this by running the following command in your terminal once you navigate to your project:</p><pre>npm install next-auth@beta</pre><p>This command will add Next Auth to your project’s dependencies, allowing you to use it for authentication.</p><h3>Step 3: Create an Auth Config File</h3><p>You will need to create a configuration file for your Next Auth setup. Navigate to your src folder and create a new file named auth.js (or auth.ts if you&#39;re using TypeScript). If you don’t have a src folder in your project than file can be created at the root of the project. In this file, we will export your Next Auth function and add the configuration for the authentication provider:</p><pre>import NextAuth from &quot;next-auth&quot;;<br>import GoogleProvider from &quot;next-auth/providers/google&quot;;</pre><pre>export const {<br>  handlers: { GET, POST },<br>  auth,<br>  signIn,<br>  signOut,<br>} = NextAuth({<br>  providers: [<br>    GoogleProvider({<br>      clientId: process.env.GOOGLE_CLIENT_ID,<br>      clientSecret: process.env.GOOGLE_CLIENT_SECRET,<br>    }),<br>  ],<br>});</pre><h3>Step 4: Configure a Provider</h3><p>The Provider dictates how users can log in to your application. This could be via email, password, or using social accounts like Google or Facebook. In this case, the Google Provider is configured. And in the next steps, we will store your Google client ID and client secret as environment variables for security purposes. These are obtained when you set up your Google OAuth credentials.</p><h3>Step 5: Create API Routes</h3><p>Next, we need the API routes that your authentication functions will use. Inside the app folder, create a new folder named api. Then, inside the api folder, create a new folder named auth. Inside auth, create another folder named [...nextauth]. Inside this folder, create a new file named route.js (or route.ts` if you&#39;re using TypeScript). This should setup the routing for your authentication functions by following code:</p><pre>// api/auth/[...nextauth]/route.ts<br>export { GET, POST } from &quot;../../../../auth&quot;;</pre><h3>Step 6: Add Environment Variables</h3><p>Next, add your Google Client ID and Google Client Secret to your .env file. We can obtain our api keys at <a href="https://console.cloud.google.com/projectselector2/apis/dashboard?pli=1&amp;supportedpurview=project">google cloud console</a>. Click “Create New Project” → Find “Credentials” Button → “Create Credentials” → Select “OAuth Client ID” → and before saving add an authorized url:</p><p><a href="http://localhost:3000/api/auth/callback/google">http://localhost:3000/api/auth/callback/google</a></p><p>This is the url that will be making a request to Google. On the way it might ask you to setup the consent screen first and details like — app name and support email. This information is what will be displayed once user is asked to login using their google account. Once you save the consent screen information you can finish creating credentials and secret and client id will show up on the screen. You can add them in .env as following:</p><pre>GOOGLE_CLIENT_ID= // your client id here<br>GOOGLE_CLIENT_SECRET= //your client secret here</pre><h3>Step 7: Add Auth Secret</h3><p>Per their new and old documentation, this step seems to be optional but I did receive an error when I hadn’t gone through it in my project, that’s why I included in this guide. In this step, you can add another variable in your .env file:</p><pre>AUTH_SECRET=</pre><p>and the value you can generate by running</p><p>openssl rand -hex 32 in your terminal OR online <a href="https://generate-secret.vercel.app/32">using this link</a></p><h3>Step 8: Test your API route</h3><p>To confirm that your API route is working correctly, navigate to localhost:3000/api/auth/signin in your browser. It should redirect you to a Google sign-in page. This means that your API route is working and your Google Provider is properly configured.</p><h3>Step 9: Add Authentication in Your Server Components</h3><p>Let’s say you have a header.tsx in your page.tsx where you want to access the user information. You can do the following:</p><pre>import { auth } from &#39;../auth&#39;; // correct path to your auth config</pre><pre>export const Header = async () =&gt; {<br>    const session = await auth();<br>     return (<br>	&lt;header&gt;<br>	     &lt;p&gt;Welcome {session.user.name}&lt;/p&gt;<br>	&lt;/header&gt;<br>)</pre><p>You can even add the login link and sign out button based on the session information:</p><pre>import { auth, signIn, signOut } from &#39;@/auth&#39;;<br>import Image from &#39;next/image&#39;;<br>import Link from &#39;next/link&#39;;<br><br>function SignOut() {<br>  return (<br>    &lt;form<br>      action={async () =&gt; {<br>        &#39;use server&#39;;<br>        await signOut();<br>      }}<br>    &gt;<br>      &lt;button type=&quot;submit&quot;&gt;Sign out&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}<br>export const Header = async (props: Props) =&gt; {<br>  const session = await auth();<br>  console.log(session);<br>  return (<br>    &lt;header&gt;<br>      &lt;nav&gt;<br>        &lt;div&gt;<br>          &lt;Link href=&quot;/&quot;&gt;&lt;h1&gt;Your Logo&lt;/h1&gt;&lt;/Link&gt;<br>          &lt;div&gt;<br>            {<br>              session?.user ? (<br>                &lt;div&gt;<br>                  {<br>                    session.user.name &amp;&amp; session.user.image &amp;&amp;<br>                    &lt;Image<br>                      src={session.user.image}<br>                      alt={session.user.name}<br>                      width={32}<br>                      height={32}<br>                    /&gt;<br>                  }<br>                  &lt;SignOut /&gt;<br>                &lt;/div&gt;<br>              ) : (<br>                &lt;Link href=&quot;/api/auth/signin&quot;&gt;<br>                  &lt;button variant=&quot;link&quot;&gt;Sign in&lt;/button&gt;<br>                &lt;/Link&gt;<br>              )<br>            }<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/nav&gt;<br>    &lt;/header&gt;<br>  )<br>}</pre><h3>Step 9: Add Authentication to your Client Components</h3><p>Now, you can begin adding authentication to your components. In your components, import the useSession hook from next-auth/react. This hook gets updated whenever there are changes to the session (i.e., when a user logs in or out). You can use this hook to conditionally render components based on whether a user is signed in. For example:</p><pre>// form.tsx<br>&#39;use client&#39;<br>import React, { useState, useEffect } from &#39;react&#39;<br>import { useSession, signIn } from &quot;next-auth/react&quot;;<br>const UserForm = () =&gt; {<br>     const session = useSession();<br>     const onSubmit = () =&gt; {<br>       if (session.status !== &quot;authenticated&quot;) {<br>         signIn(); // will re-direct to sign in page<br>       } else {<br>         // do something else<br>        }<br> return (<br>    &lt;form onSubmit={onSubmit}&gt;<br>       &lt;input type=&quot;text&quot; placeholder=&quot;Your name&quot;/&gt;<br>       &lt;button type=&quot;submit&quot; /&gt;<br>    &lt;/form&gt;<br> )<br>};</pre><p>But before you can test out session on your client components you have to do:</p><h3>Step 10: Wrap your application in a Provider</h3><p>The final step is to wrap your application in a SessionProvider from next-auth/react. This allows you to use the useSession hook in your components. You can either wrap your entire application in this provider, or just the individual components that need access to session information.</p><pre>import { SessionProvider } from &quot;next-auth/react&quot;<br>export default function App() {<br>	&lt;SessionProvider&gt;<br>		// rest of your application<br>	&lt;/SessionProvider&gt;<br>}</pre><p>Congratulations! You have now integrated authentication into your Next.js project using Next Auth. Your users can now sign in to your application using their Google accounts.</p><p>After the integration, I also connected the auth to my database, it’s part of the project tutorial, which if you want to follow along <a href="https://youtu.be/zzWypOl4JkY">can check it out here</a>🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d57f84cf4ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I integrated Stripe Payments in React App]]></title>
            <link>https://judy-webdecoded.medium.com/how-i-integrated-stripe-payments-in-react-app-db24cd5c200b?source=rss-17b9f0fce28f------2</link>
            <guid isPermaLink="false">https://medium.com/p/db24cd5c200b</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[stripe-integration]]></category>
            <dc:creator><![CDATA[Judy@webdecoded]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 20:10:45 GMT</pubDate>
            <atom:updated>2023-10-02T20:10:45.243Z</atom:updated>
            <content:encoded><![CDATA[<p>To integrate Stripe into an application, a server-side component is required. The server-side component is responsible for securely handling sensitive information, such as payment details, and communicating with Stripe’s APIs. Since React is a client-side library, it needs a server(unless you’re using its framework like NextJS) to be able to process payments. The flow would be following: Build a form that takes in user information such as payment details and etc, the client-side code(React) sends a request to the server. The server-side code then interacts with Stripe’s APIs to create a payment intent, which includes the necessary information for processing the payment. Because I didn’t need backend functionalities for the rest of my application, and didn’t want to go through the hassle of creating a backend, such as MongoDB, setting up the Express framework, creating APIs, and deploying it, I chose to use a platform that would enable me to deploy <strong>serverless functions</strong> — <a href="https://aircode.io/">Aircode</a>. Each function would handle different step of Stripe payment:</p><ol><li>Generating payment intent</li><li>Monitoring payment status</li></ol><p>And the React steps would include :</p><ol><li>Capturing user data once user starts filling out the form and sending the request to API(Step 1 in backend) when user submits the form</li><li>Confirming the Client success(basically a token returned when payment intent is generated) using stripe package .</li></ol><p>Here’s a quick diagram of what’s happening:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVJZgB05GaKfI7jU9lhEfQ.png" /></figure><p>Now let’s dive into code ✍️</p><p>To be able to successfully run the code you will need <a href="https://dashboard.stripe.com/developers">Stripe developer account</a> and its public and private keys, which can be obtained by going into the dashboard, creating a new project and navigating to <strong>API keys</strong> tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhIZF2lJ56duVpF28f_JZg.png" /><figcaption>Stripe Dashboard</figcaption></figure><p>First, I added a <a href="https://www.npmjs.com/package/@stripe/react-stripe-js">stripe module</a> in my react project:</p><pre>npm install @stripe/react-stripe-js @stripe/stripe-js</pre><p>And created a container component in which I will initialize stripe instance using the <strong>publishable key:</strong></p><pre>import React from &#39;react&#39;<br>import { loadStripe } from &#39;@stripe/stripe-js&#39;;<br>import {<br>  Elements,<br>} from &#39;@stripe/react-stripe-js&#39;;<br>import { CheckoutForm } from &#39;../components/CheckoutForm&#39;<br><br>type Props = {}<br><br>const options = {<br>  mode: &#39;payment&#39;,<br>  amount: 1099,<br>  currency: &#39;usd&#39;,<br>  // Fully customizable with appearance API.<br>  appearance: {<br>    /*...*/<br>  },<br>};<br><br>const Checkout = (props: Props) =&gt; {<br>  const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PK);<br>  // import meta.env.VITE_STRIPE_PK is the publishable key you can either directly paste your stripe key here but not recommending if you are planning to upload the code on github as it should remain only available to you or save the key in .env file<br>  <br>  return (<br>    &lt;div className=&#39;flex container mt-8&#39;&gt;<br>      &lt;Elements stripe={stripePromise} options={options}&gt;<br>        &lt;CheckoutForm /&gt;<br>      &lt;/Elements&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default Checkout</pre><p>And my publishable key is saved in .env file like this:</p><pre>// .env<br>VITE_STRIPE_PK=&quot;your key&quot;</pre><p>Please note this syntax varies depending on how you created your react app, I personally used <a href="https://vitejs.dev/guide/env-and-mode.html">Vite</a>, that’s why I prefix my variables with “VITE_” otherwise compiler won’t be able to read it, but if for example you used create-react-app you would need to switch it with “REACT_APP_…” more about it <a href="https://create-react-app.dev/docs/adding-custom-environment-variables/">here</a>.</p><p>And the checkout form that is used stripe functions inside <strong>Elements provider </strong>looks like this:</p><pre>import React, { useState } from &#39;react&#39;;<br>import {<br>  PaymentElement,<br>  Elements,<br>  useStripe,<br>  useElements,<br>} from &#39;@stripe/react-stripe-js&#39;;<br><br>export const CheckoutForm = () =&gt; {<br>  const stripe = useStripe();<br>  const elements = useElements();<br><br>  const [errorMessage, setErrorMessage] = useState(&#39;&#39;);<br>  const [emailInput, setEmailInput] = useState(&#39;&#39;);<br><br>  const backendUrl = import.meta.env.VITE_STRIPE_PK_AIRCODE_URL;<br><br>  const handleSubmit = async (event) =&gt; {<br>    event.preventDefault();<br><br>    if (elements == null || stripe == null) {<br>      return;<br>    }<br><br>    // Trigger form validation and wallet collection<br>    const { error: submitError } = await elements.submit();<br>    if (submitError?.message) {<br>      // Show error to your customer<br>      setErrorMessage(submitError.message);<br>      return;<br>    }<br><br>    const price = 12;<br><br>    // Create the PaymentIntent and obtain clientSecret from your server endpoint<br>    const res = await fetch(backendUrl, {<br>      method: &#39;POST&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      },<br>      body: JSON.stringify({<br>        currency: &#39;usd&#39;,<br>        email: emailInput,<br>        amount: price * 100,<br>        paymentMethodType: &quot;card&quot;<br>      }),<br>    });<br><br>    const { client_secret: clientSecret } = await res.json();<br><br>    const { error } = await stripe.confirmPayment({<br>      //`Elements` instance that was used to create the Payment Element<br>      elements,<br>      clientSecret,<br>      confirmParams: {<br>        return_url: `${window.location.origin}/success`,<br>      },<br>    });<br><br>    if (error) {<br>      // This point will only be reached if there is an immediate error when<br>      // confirming the payment. Show error to your customer (for example, payment<br>      // details incomplete)<br>      setErrorMessage(error.message);<br>    } else {<br>      // Your customer will be redirected to your `return_url`. For some payment<br>      // methods like iDEAL, your customer will be redirected to an intermediate<br>      // site first to authorize the payment, then redirected to the `return_url`.<br>    }<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit} className=&#39;px-4&#39;&gt;<br>      &lt;div className=&#39;mb-3&#39;&gt;<br>        &lt;label htmlFor=&quot;email-input&quot;&gt;Email&lt;/label&gt;<br>        &lt;div&gt;<br>          &lt;input value={emailInput} onChange={(e =&gt; setEmailInput(e.target.value))} type=&quot;email&quot; id=&quot;email-input&quot; placeholder=&#39;johndoe@gmail.com&#39; /&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;PaymentElement /&gt;<br>      &lt;button type=&quot;submit&quot; disabled={!stripe || !elements}&gt;<br>        Pay<br>      &lt;/button&gt;<br>      {/* Show error message to your customers */}<br>      {errorMessage &amp;&amp; &lt;div&gt;{errorMessage}&lt;/div&gt;}<br>    &lt;/form&gt;<br>  );<br>};</pre><p>Now only thing we are missing is Aircode URL, which will serve as an access point to our backend, head to <a href="https://aircode.io/">Aircode</a> to create a new account and + New NodeJS App with these settings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*Sv48g86vJFziLxzxoNxYwA.png" /><figcaption>New NodeJs App</figcaption></figure><p>On the left menu of the project select Environments and Add a new key value pair, where we have STRIPE_SECRET_KEY and as a value paste the Secret Key from the Stripe Dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*IVOV2W-TSbgJUuWnHWrhUA.png" /></figure><p>Each file in our project setup will serve as a function and we can either rename the started file provided by AirCode or create a new file and name it — payment.ts and paste the following code in there:</p><pre>// @see https://docs.aircode.io/guide/functions/<br>import aircode from &quot;aircode&quot;;<br>import Stripe from &quot;stripe&quot;;<br><br>type Params = {<br>  email: string;<br>  amount: number;<br>  currency: string;<br>  paymentMethodType: string;<br>};<br><br>export default async function (params: Params, context: any) {<br>  console.log(&quot;Received params:&quot;, params);<br>  const { email, amount, currency, paymentMethodType } = params;<br><br>  if (process.env.STRIPE_SECRET_KEY) {<br>    const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {<br>      apiVersion: &quot;2023-08-16&quot;,<br>      typescript: true,<br>    });<br><br>    try {<br>      const paymentIntent = await stripe.paymentIntents.create({<br>        amount,<br>        currency,<br>      });<br><br>      const payment_id = paymentIntent.id;<br><br>      context.status(200);<br>      return {<br>        client_secret: paymentIntent.client_secret,<br>      };<br>    } catch (e: any) {<br>      context.status(500);<br>      console.log(e);<br>      return {<br>        message: e.message,<br>      };<br>    }<br>  }<br><br>  return {<br>    message: &quot;Please add stripe api key&quot;,<br>  };<br>}</pre><p>Now you might see a red line under the code `import Stripe from “stripe”;` that’s because we also have to install stripe node js module and we’ll do that on the left side by going to <strong>Dependencies</strong> and selecting stripe from options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*xbzvLSNBEZtKNkYy9_V-6w.png" /><figcaption>AirCode Project Dependencies</figcaption></figure><p>Once the function is ready at the top of the toolbar you will press <strong>Deploy </strong>that will generate a url that you can copy and paste it into your React App’s .env file:</p><pre>// .env<br>VITE_STRIPE_PK=&quot;your key&quot;<br>VITE_STRIPE_PK_AIRCODE_URL=&quot;your aircode url&quot;</pre><p>This value is used by our <strong>CheckoutForm </strong>to make a request to API, get the client success and than on the client side we call <strong>stripe.confirmPayment </strong>to confirm the payment and finally we pass it redirect url where in case of success we want stripe module to redirect our users to.</p><p>This is the full github url: <a href="https://github.com/judygab/digital-product-tutorial/">https://github.com/judygab/digital-product-tutorial/</a></p><p>And for deeper dive you can also watch the video tutorial of the project I integrated payments in:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FO7iy6PS5IhM%3Fstart%3D2674%26feature%3Doembed%26start%3D2674&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DO7iy6PS5IhM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FO7iy6PS5IhM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aa8b07d479aa87a7d9d32e7093ce450/href">https://medium.com/media/6aa8b07d479aa87a7d9d32e7093ce450/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db24cd5c200b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own AI Chatbot with ChatGPT API]]></title>
            <link>https://judy-webdecoded.medium.com/build-your-own-ai-chatbot-with-chatgpt-api-e82ce11fae1d?source=rss-17b9f0fce28f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e82ce11fae1d</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Judy@webdecoded]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 03:19:02 GMT</pubDate>
            <atom:updated>2023-03-21T03:20:24.297Z</atom:updated>
            <content:encoded><![CDATA[<p>OpenAI&#39;s recent introduction of the ChatGPT API has made it very simple to build an AI chatbot and integrate it into a website. In this article, we will build a user interface for the chat, integrate the OpenAI API, and deploy the chat so that users can have a conversation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Y_J00nzkUCKne1PTrXQ1A.png" /><figcaption>chatbot futuristic ui mobile mockup</figcaption></figure><p>If you prefer to follow a video tutorial, here’s the link:</p><p><a href="https://www.youtube.com/watch?v=WsYABsWMFqc">https://www.youtube.com/watch?v=WsYABsWMFqc</a></p><p><strong>OpenAI</strong></p><p>To be able to use the API you would have to:</p><ol><li>Create an account at <a href="https://platform.openai.com/">https://platform.openai.com/</a></li><li>Enable billing &amp; get API keys at <a href="https://platform.openai.com/account/api-keys">https://platform.openai.com/account/api-keys</a></li></ol><p><strong>Project Setup</strong></p><p>We initialize the project by running this in terminal:</p><pre>npx create-next-app@latest ai-chatbot --js --tailwind --src-dir</pre><p>We navigate to the project:</p><pre>cd ai-chatbot</pre><p><strong>Configure Environment Variables</strong></p><p>The API key that we got in the first part from OpenAI, we can store that by creating a new .env.local file in the root of the project and adding the key in it:</p><pre>NEXT_PUBLIC_OPENAI_KEY=YourKeyHere</pre><p>We will install <a href="https://axios-http.com/docs/intro">axios</a> to fetch data and run our application:</p><pre>npm install axios &amp;&amp; npm run dev</pre><p>Unless the port is taken this should start the application at <a href="http://localhost:3000/">http://localhost:3000/</a></p><p>Inside index.js which is our main page, we can call the API and fetch data.</p><p>First, let’s import the axios and inside the main component create the function:</p><pre>// index.js<br>import axios from &#39;axios&#39;;<br><br>....<br>const sendMessage = (message) =&gt; {<br>    const url = &#39;&lt;https://api.openai.com/v1/chat/completions&gt;&#39;; // OpenAI API endpint<br>		<br>		const headers = {<br>			&#39;Content-type&#39;: &#39;application/json&#39;,<br>			&#39;Authorization&#39;: `Bearer ${process.env.NEXT_PUBLIC_OPENAI_KEY}`<br>		}<br><br>    const data = {<br>      model: &quot;gpt-3.5-turbo-0301&quot;, // the model that we want to use<br>      messages: [{ &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message }]<br>    };<br><br>    setIsLoading(true);<br><br>    axios.post(url, data, headers).then((response) =&gt; {<br>      console.log(response);<br>    }).catch((error) =&gt; {<br>      console.log(error);<br>    })<br>  }</pre><p>This function sends a POST request to the OpenAI API endpoint with a message provided by the user. The response will contain the chatbot&#39;s reply, which can be displayed to the user. We are also passing headers that contains an API key that is getting loaded from environment variables.</p><p>We can now use the sendMessage function to display the chatbot&#39;s response. We can do this by creating a new state variable to store the chat messages and updating it with the chatbot&#39;s response. We can also display the chat messages in the UI as a chat log.</p><pre>import { useState, useEffect } from &quot;react&quot;;<br><br>export default function Home() {<br>const [inputValue, setInputValue] = useState(&#39;&#39;);<br>const [chatLog, setChatLog] = useState([]);<br>const [isLoading, setIsLoading] = useState(false);<br><br>const sendMessage = (message) =&gt; {<br>    const url = &#39;&lt;https://api.openai.com/v1/chat/completions&gt;&#39;;<br><br>    const data = {<br>      model: &quot;gpt-3.5-turbo-0301&quot;,<br>      messages: [{ &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message }]<br>    };<br><br>		const headers = {<br>			&#39;Content-type&#39;: &#39;application/json&#39;,<br>			&#39;Authorization&#39;: `Bearer ${process.env.NEXT_PUBLIC_OPENAI_KEY}`<br>		}<br><br>    setIsLoading(true);<br><br>    axios.post(url, data, headers).then((response) =&gt; {<br>      console.log(response);<br>      setChatLog((prevChatLog) =&gt; [...prevChatLog, { type: &#39;bot&#39;, message: response.data.choices[0].message.content }])<br>      setIsLoading(false);<br>    }).catch((error) =&gt; {<br>      setIsLoading(false);<br>      console.log(error);<br>    })<br>  }<br><br>// rest of the component<br>}</pre><p>Finally, we can add an input field for the user to type their message and a button to send it to the chatbot.</p><pre>// index.js<br>...<br>return (<br>	&lt;form&gt;<br>		&lt;input type=&quot;text&quot; placeholder=&quot;Type your message...&quot; value={inputValue} onChange={(e) =&gt; setInputValue(e.target.value)}/&gt;<br>		&lt;button type=&quot;submit&quot;&gt;Send&lt;/button&gt;<br>	&lt;/form&gt;<br>)</pre><p>After adding the input field and button, we can handle the submission of messages by calling the sendMessage function with the current value of the input field. We can also display the chat log in the UI by mapping over the chatLog state variable and rendering each message as a separate chat bubble:</p><pre>import { useState, useEffect } from &quot;react&quot;;<br>import axios from &#39;axios&#39;;<br><br>export default function Home() {<br>const [inputValue, setInputValue] = useState(&#39;&#39;);<br>const [chatLog, setChatLog] = useState([]);<br>const [isLoading, setIsLoading] = useState(false);<br><br>const sendMessage = (message) =&gt; {<br>    const url = &#39;&lt;https://api.openai.com/v1/chat/completions&gt;&#39;;<br><br>    const data = {<br>      model: &quot;gpt-3.5-turbo-0301&quot;,<br>      messages: [{ &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message }]<br>    };<br><br>		const headers = {<br>			&#39;Content-type&#39;: &#39;application/json&#39;,<br>			&#39;Authorization&#39;: `Bearer ${process.env.NEXT_PUBLIC_OPENAI_KEY}`<br>		}<br><br>    setIsLoading(true);<br><br>    axios.post(url, data, headers).then((response) =&gt; {<br>      console.log(response);<br>      setChatLog((prevChatLog) =&gt; [...prevChatLog, { type: &#39;bot&#39;, message: response.data.choices[0].message.content }])<br>      setIsLoading(false);<br>    }).catch((error) =&gt; {<br>      setIsLoading(false);<br>      console.log(error);<br>    })<br>  }<br><br>const handleSubmit = (event) =&gt; {<br>    event.preventDefault();<br><br>    setChatLog((prevChatLog) =&gt; [...prevChatLog, { type: &#39;user&#39;, message: inputValue }])<br><br>    sendMessage(inputValue);<br>    <br>    setInputValue(&#39;&#39;);<br>  }<br><br>return (<br>	&lt;div&gt;<br>		&lt;div&gt;<br>			{chatLog.map((message, index) =&gt; (<br>						&lt;div key={index}&gt;{message.message}&lt;/div&gt;<br>				)}<br>		&lt;/div&gt;<br>		&lt;form onSubmit={handleSubmit}&gt;<br>			&lt;input type=&quot;text&quot; placeholder=&quot;Type your message...&quot; value={inputValue} onChange={(e) =&gt; setInputValue(e.target.value)}/&gt;<br>			&lt;button type=&quot;submit&quot;&gt;Send&lt;/button&gt;<br>		&lt;/form&gt;<br>	&lt;/div&gt;<br>)<br><br>}</pre><p>HandleSubmit will take the user input, append it to the messages displayed on the screen, and make a call to the API to get the data. It will also reset the user input field.</p><p>Finally, we can add some styling using Tailwind utility classes and the final result would be:</p><pre>import { useState, useEffect } from &quot;react&quot;;<br>import axios from &#39;axios&#39;;<br><br>export default function Home() {<br>  const [inputValue, setInputValue] = useState(&#39;&#39;);<br>  const [chatLog, setChatLog] = useState([]);<br>  const [isLoading, setIsLoading] = useState(false);<br><br>  const handleSubmit = (event) =&gt; {<br>    event.preventDefault();<br><br>    setChatLog((prevChatLog) =&gt; [...prevChatLog, { type: &#39;user&#39;, message: inputValue }])<br><br>    sendMessage(inputValue);<br>    <br>    setInputValue(&#39;&#39;);<br>  }<br><br>const sendMessage = (message) =&gt; {<br>    const url = &#39;&lt;https://api.openai.com/v1/chat/completions&gt;&#39;;<br><br>    const data = {<br>      model: &quot;gpt-3.5-turbo-0301&quot;,<br>      messages: [{ &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message }]<br>    };<br><br>		const headers = {<br>			&#39;Content-type&#39;: &#39;application/json&#39;,<br>			&#39;Authorization&#39;: `Bearer ${process.env.NEXT_PUBLIC_OPENAI_KEY}`<br>		}<br><br>    setIsLoading(true);<br><br>    axios.post(url, data, headers).then((response) =&gt; {<br>      console.log(response);<br>      setChatLog((prevChatLog) =&gt; [...prevChatLog, { type: &#39;bot&#39;, message: response.data.choices[0].message.content }])<br>      setIsLoading(false);<br>    }).catch((error) =&gt; {<br>      setIsLoading(false);<br>      console.log(error);<br>    })<br>  }<br><br>  return (<br>    &lt;div className=&quot;container mx-auto max-w-[700px]&quot;&gt;<br>      &lt;div className=&quot;flex flex-col h-screen bg-gray-900&quot;&gt;<br>        &lt;h1 className=&quot;bg-gradient-to-r from-blue-500 to-purple-500 text-transparent bg-clip-text text-center py-3 font-bold text-6xl&quot;&gt;ChatGPT&lt;/h1&gt;<br>        &lt;div className=&quot;flex-grow p-6&quot;&gt;<br>          &lt;div className=&quot;flex flex-col space-y-4&quot;&gt;<br>          {<br>        chatLog.map((message, index) =&gt; (<br>          &lt;div key={index} className={`flex ${<br>            message.type === &#39;user&#39; ? &#39;justify-end&#39; : &#39;justify-start&#39;<br>            }`}&gt;<br>            &lt;div className={`${<br>              message.type === &#39;user&#39; ? &#39;bg-purple-500&#39; : &#39;bg-gray-800&#39;<br>            } rounded-lg p-4 text-white max-w-sm`}&gt;<br>            {message.message}<br>            &lt;/div&gt;<br>            &lt;/div&gt;<br>        ))<br>            }<br>      &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;form onSubmit={handleSubmit} className=&quot;flex-none p-6&quot;&gt;<br>          &lt;div className=&quot;flex rounded-lg border border-gray-700 bg-gray-800&quot;&gt;  <br>        &lt;input type=&quot;text&quot; className=&quot;flex-grow px-4 py-2 bg-transparent text-white focus:outline-none&quot; placeholder=&quot;Type your message...&quot; value={inputValue} onChange={(e) =&gt; setInputValue(e.target.value)} /&gt;<br>            &lt;button type=&quot;submit&quot; className=&quot;bg-purple-500 rounded-lg px-4 py-2 text-white font-semibold focus:outline-none hover:bg-purple-600 transition-colors duration-300&quot;&gt;Send&lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/form&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>We now have a fully functional chatbot! Users can type messages, the chatbot will generate a response, and the conversation will be displayed in the UI as a chat log. However, there is always room for improvement. For example, we could add more features to the UI such as the ability to display images or video, text-to-speech and etc. Additionally, we could integrate the chatbot with other services such as a CRM system or a payment gateway. The possibilities are endless!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e82ce11fae1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Text Animation with React and Framer Motion]]></title>
            <link>https://towardsdev.com/create-a-text-animation-with-react-and-framer-motion-beec5ab1aa07?source=rss-17b9f0fce28f------2</link>
            <guid isPermaLink="false">https://medium.com/p/beec5ab1aa07</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[framer-motion]]></category>
            <dc:creator><![CDATA[Judy@webdecoded]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 21:55:55 GMT</pubDate>
            <atom:updated>2023-02-14T16:26:35.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnBOtHwZDz-mm_RT59Whkw.gif" /><figcaption>text animation demo</figcaption></figure><p>Creating text animations with React and Framer Motion is a great way to add dynamic visual elements to your web pages. In this blog post, we’ll be exploring how to use the two libraries together to create stunning text animations. Firstly, we’ll discuss the setup process for React and Framer Motion, covering the installation and configuration of the libraries and the creation of a basic React application.</p><p>Once you have installed the libraries, you can start creating a React application.</p><p>To do this, you will need to initialize a React project using the command npx create-react-app &lt;name-of-project&gt;. This will create a new React project with all the necessary files and folders. Once the project is initialized, you can start writing code to create text animation with React and Framer Motion.</p><p>In order to create a TextAnimation component in React, we need to create a new file and import it into App.js. To create the file, we can use any text editor or IDE and save it in the src directory of the React project. In this file, we&#39;ll write the code for our TextAnimation component.</p><p>The code for the TextAnimation component will include the import statement to import the motion library from Framer Motion, and the component itself.</p><p>Finally, we need to import the TextAnimation component into App.js. To do this, we can use the import statement to specify the file path of the TextAnimation component, and then add the component to the render() method of App.js.</p><pre>// App.js<br><br>import React from &#39;react&#39;;<br>import TextAnimation from &#39;./TextAnimation&#39;;<br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;TextAnimation /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>Once the TextAnimation component is imported into App.js and the animation properties are set, we can start creating text animations with React and Framer Motion.</p><p>Our code will need to include components for the animation, define the animation properties, and make sure the animation runs smoothly. Let’s start by creating a component for the animation:</p><pre>import { motion } from &quot;framer-motion&quot;;<br><br>const TextAnimation = () =&gt; {<br>  return (<br>    &lt;motion.div&gt;<br>        &lt;motion.span<br>          initial={{ opacity: 0 }}<br>          animate={{ opacity: 1 }}<br>        &gt;Hello World<br>        &lt;/motion.span&gt;<br>    &lt;/motion.div&gt;<br>  );<br>};<br>export default TextAnimation;</pre><p>This code creates a motion.span component with a animate property that defines the animation properties. In this case, we&#39;re setting the opacity to animate from 0 to 1 and pass the property to the initial and animate which are different states of the animation. We can also customize the animation further to make it look and feel just as we want it to. For now, our text has animation where is appears from hidden state.</p><p>To display each letter one by one, we can use the transition props on the motion.span component. We can create a variable text that we will set to the string we want to get displayed and map the letters out. For example:</p><pre>// TextAnimation.js<br>const text = &quot;Hello world&quot;;<br><br>return (<br>    &lt;motion.div&gt;<br>      {text.split(&quot;&quot;).map((letter, index) =&gt; (<br>        &lt;motion.span<br>          key={index}<br>          initial={{ opacity: 0 }}<br>          animate={{ opacity: 1 }}<br>          transition={{ duration: 0.2, delay: index * 0.1 }}<br>        &gt;<br>          {letter}<br>        &lt;/motion.span&gt;<br>      ))}<br>    &lt;/motion.div&gt;<br>  );</pre><p>What this will do is that on every next letter that would be displayed it will increase the delay so they show up one after the other.</p><p>Finally, if you want to add the same styling as I have in the example, you can add a class=&quot;text&quot; to motion.div and some css from below:</p><pre>// TextAnimation.js<br>import { motion } from &quot;framer-motion&quot;;<br><br>const TextAnimation = () =&gt; {<br>  const text = &quot;Hello world&quot;;<br>  return (<br>    &lt;motion.div className=&quot;text&quot;&gt;<br>      {text.split(&quot;&quot;).map((letter, index) =&gt; (<br>        &lt;motion.span<br>          key={index}<br>          initial={{ opacity: 0 }}<br>          animate={{ opacity: 1 }}<br>          transition={{ duration: 0.2, delay: index * 0.1 }}<br>        &gt;<br>          {letter}<br>        &lt;/motion.span&gt;<br>      ))}<br>    &lt;/motion.div&gt;<br>  );<br>}<br>export default TextAnimation;</pre><pre>// styles.css<br><br>.App {<br>  font-family: sans-serif;<br>  text-align: center;<br>  background-color: #0D1117;<br>  height: 100vh;<br>  width: 100%;<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>}<br>.text {<br>  font-size: 36px;<br>  text-transform: uppercase;<br>  color: white;<br>  font-weight: bold;<br>  text-transform: uppercase;<br> background: linear-gradient(to right, #30CFD0 0%, #330867 100%);<br> -webkit-background-clip: text;<br> -webkit-text-fill-color: transparent;<br>}</pre><p>And that would be all:)</p><p>For more animations, check out the tutorial:</p><p><a href="https://youtu.be/xwFzvBhcd0k">https://youtu.be/xwFzvBhcd0k</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beec5ab1aa07" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/create-a-text-animation-with-react-and-framer-motion-beec5ab1aa07">Create a Text Animation with React and Framer Motion</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create React Typing Animation — Quick Tutorial]]></title>
            <link>https://towardsdev.com/create-react-typing-animation-quick-tutorial-ec0c102e7afd?source=rss-17b9f0fce28f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec0c102e7afd</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Judy@webdecoded]]></dc:creator>
            <pubDate>Wed, 22 Jun 2022 01:57:21 GMT</pubDate>
            <atom:updated>2022-06-30T04:24:20.103Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create React Typing Animation — Quick Tutorial</h3><p>React typing animation is popular, especially among personal portfolio websites. Creators use it to describe themselves from different angles and rather than just listing who they are, we get a text typing animation that slowly lists it for us, focusing on one aspect each time.</p><p>This animation is actually easy to achieve and will go through how in this article without any additional packages. If you are also not a fan of loading your project with packages that are just for one functionality, this tutorial is perfect for you :)</p><p>Here’s an example of what we will be building:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Zf4OqVGxo2OJpJmw5qV7RA.gif" /><figcaption>React Typing Animation Example</figcaption></figure><p>There are a few things we would need to track here: text current text on the screen, typingSpeed the speed in milliseconds in which typing proceeds, isDeleting if currently word is being typed out or another way around: being deleted, loopNum on which word from the list we are at currently, toRotate the list of words we want to display, and switchSpeed the speed by which we want to replace words, so the time between when a word has been deleted and when we start typing out a new word. Out of these only toRotate and switchSpeed will not get updated throughout the application, so we will create them as constants, as for the rest, they will be stored as react state:</p><pre>import { useState, useEffect } from &quot;react&quot;;</pre><pre>export default function App() {</pre><pre>   const [text, setText] = useState(&quot;&quot;);</pre><pre>   const [loopNum, setLoopNum] = useState(0);</pre><pre>   const [isDeleting, setIsDeleting] = useState(false);</pre><pre>   const [typeSpeed, setTypeSpeed] = useState(300 - Math.random() * 100);</pre><pre>   const toRotate = [&quot;Web Developer&quot;, &quot;Web Designer&quot;, &quot;UI/UX Designer&quot;];</pre><pre>   const switchSpeed = 2000;</pre><pre>return (<br>    &lt;div className=&quot;App&quot;&gt;</pre><pre>      &lt;div className=&quot;typing-container&quot;&gt;</pre><pre>        &lt;h4&gt;Welcome to my website&lt;/h4&gt;</pre><pre>        &lt;h1&gt;Hi I&#39;m J! &lt;br&gt;&lt;/br&gt;</pre><pre>           &lt;span className=&quot;txt-rotate&quot;&gt;{text}&lt;/span&gt;</pre><pre>        &lt;/h1&gt;</pre><pre>      &lt;/div&gt;</pre><pre>    &lt;/div&gt;</pre><pre>);</pre><p>Right now, we won’t see any text below our h4, because nothing triggers its updates, to do that we will make use of useEffect and include a function inside that will be responsible for updating the text, as for the frequency this function will be fired will be set to typeSpeed . So we would have the following:</p><pre>useEffect(() =&gt; {</pre><pre>  let ticker = setInterval(() =&gt; {</pre><pre>    tick();</pre><pre>  }, typeSpeed);</pre><pre>   return () =&gt; { clearInterval(ticker); };</pre><pre>}, [text]);</pre><p>Since we are using setInterval, we need to make sure that we clear it once the component unmounts thus having it in the return statement of useEffect . As for the dependency we set it as text because if we didn’t trigger `useEffect` every time text updates, then the function tick every time will have access to the old copy of the state and we need the new one instead. Now let’s define our method:</p><pre>const tick = () =&gt; {</pre><pre>   let i = loopNum % toRotate.length;</pre><pre>   let fullText = toRotate[i];</pre><pre>   let updatedText = isDeleting ? fullText.substring(0, text.length - 1)</pre><pre>: fullText.substring(0, text.length + 1);</pre><pre>   setText(updatedText);</pre><pre>   if (isDeleting) { setTypeSpeed((prevSpeed) =&gt; prevSpeed / 2);}</pre><pre>   if (!isDeleting &amp;&amp; updatedText === fullText) {</pre><pre>     setIsDeleting(true);</pre><pre>     setTypeSpeed(switchSpeed);</pre><pre>   } else if (isDeleting &amp;&amp; updatedText === &quot;&quot;) {</pre><pre>     setIsDeleting(false);</pre><pre>     setLoopNum(loopNum + 1);</pre><pre>     setTypeSpeed(switchSpeed);</pre><pre>   }</pre><pre>};</pre><p>So what happening here?</p><p>We have a counter loopNum that increments every time we finish typing the current word and replace it with the new one. Since we want to access the next word and this counter increments indefinitely, at some point it will become higher than the length of the array of words that we have, that is when we have to go around the circle and come back at the beginning, so basically taking module of the length of the array and setting it to i index.</p><p>Once we have the current index, we get the full word — fullText. Now we want to calculate what the next text to be displayed on screen should be, this is done with the help of isDeleting, which tells us if we should take the length of the current text and add one letter to it from the full text and subtract it. Once we have that calculated, we update the state of text so it actually gets displayed on the screen. Than let’s see what happens to the speed. The way I have it, I want the backward speed to be twice faster than the normal speed, so it resembles better the natural speed of human typing, but this is totally optional: so I’m checking if isDeleting is on, take the speed and divide by 2 compared to the previous one. Also everytime we update a word we need to check 2 conditions: are we done typing the word or are we done deleting the word? We care about these because we need to update isDeleting, loopNum , and typeSpeed accordingly. So we check 2 things: if isDeleting is on and if the current text is equal to the full text(that would tell us that we are done typing it out) or if it’s completely empty(that tells us that we are done deleting, let’s move on to the next word by updating loopNum, and putting back our normal typing speed — typeSpeed. If you want to add the same styling as I did, here it is:</p><pre>.App {</pre><pre>  font-family: sans-serif;</pre><pre>  text-align: center;</pre><pre>  background-color: #790cb5;</pre><pre>  width: 100%;</pre><pre>  height: 100%;</pre><pre>}</pre><pre>body,#root {</pre><pre>  height: 100vh;</pre><pre>  margin: 0;</pre><pre>  color: white;</pre><pre>  box-sizing: border-box;</pre><pre>  display: flex;</pre><pre>  width: 100%;</pre><pre>}</pre><pre>.txt-rotate {</pre><pre>  color: yellow;</pre><pre>}</pre><p>And the sandbox link for the full code:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F6szw7x&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F6szw7x&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F6szw7x%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/a08574124937af8f07984d01ffca2727/href">https://medium.com/media/a08574124937af8f07984d01ffca2727/href</a></iframe><p>Happy Reacting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec0c102e7afd" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/create-react-typing-animation-quick-tutorial-ec0c102e7afd">Create React Typing Animation — Quick Tutorial</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Different Ways of Downloading Files in React App]]></title>
            <link>https://towardsdev.com/different-ways-of-downloading-files-in-react-app-c2eef6ee59e3?source=rss-17b9f0fce28f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2eef6ee59e3</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[file-save]]></category>
            <dc:creator><![CDATA[Judy@webdecoded]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 21:58:49 GMT</pubDate>
            <atom:updated>2022-08-03T06:48:48.426Z</atom:updated>
            <content:encoded><![CDATA[<p>Whether we want to use plain JavaScript to accomplish this or a third-party module, this functionality can be easily achieved in React. I will be going over both methods while demonstrating them with code snippets. They also work on different file types, like csv, xlsx, rtf and etc. In this example, we will be downloading an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLbqYQJazn1JA4pmku2K6g.png" /><figcaption>File Download in React</figcaption></figure><p>First, let’s see how we can do this without any extra packages. The way it works is that when the user clicks ‘Download’:</p><ol><li>Create an a href element</li><li>Create a DOMString containing a URL representing the blob of our file, using createObjectURL method</li><li>Pointing href of our a element to the URL</li><li>Setting the download attribute that determines the name of the file that will be downloaded.</li><li>Firing click on a element</li><li>Removing the URL from the element, since we used it to hold the blob address temporarily.</li></ol><p>The method would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GYxlLd4k5jHoYXjwmkLaZA.png" /><figcaption>Download a file in React</figcaption></figure><p>The step that we need in all methods to download the file, is converting that file to Blob. Blobs represent raw, immutable data. In fact, File is an extension of Blob. Most browsers support blobs, and we use them to hold the data, like the information about size, name, and the contents of the file.</p><p>Now, let’s do the same using <a href="https://www.npmjs.com/package/file-saver">file-saver</a>. This package makes it very simple to save files on the client-side. We can install it using the command:</p><pre>npm install --save file-saver </pre><p>and import its method saveAs at the top of our component file:</p><pre><strong>import</strong> { saveAs } <strong>from</strong> &#39;file-saver&#39;;</pre><p>And finally, we can write the download method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcWx50_0UzOVwpmzuBHfwA.png" /><figcaption>Download file in React using file-saver</figcaption></figure><p>Once we convert the file into a blob, we can call the method from the module saveAs and pass two arguments: the blob and the name of the file. It’s as simple as that :)</p><p>For the codesandbox link of the full code, <a href="https://codesandbox.io/s/download-file-bimeoj?file=/src/App.js">click here</a>.</p><p>Also, don’t forget to follow me on <a href="https://github.com/judygab">GitHub</a> to see projects I implement these code snippets in:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2eef6ee59e3" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/different-ways-of-downloading-files-in-react-app-c2eef6ee59e3">Different Ways of Downloading Files in React App</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency and Transitions in React]]></title>
            <link>https://judy-webdecoded.medium.com/concurrency-and-transitions-in-react-bc5db22a816c?source=rss-17b9f0fce28f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc5db22a816c</guid>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Judy@webdecoded]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 00:16:58 GMT</pubDate>
            <atom:updated>2022-06-07T17:34:59.907Z</atom:updated>
            <content:encoded><![CDATA[<h4>One of the biggest updates in React 18 is that it supports concurrency. Let’s look at what that means first before we jump into the specific features. By definition concurrency is:</h4><blockquote>the ability of different parts or units of a program, algorithm, or problem to be executed out-of-order or in partial order, without affecting the final outcome.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*UJSbeE3ckNv32dm9cXzpsQ.gif" /><figcaption><a href="https://codemyui.com/pure-css-skeleton-screen-gleam-animation-for-light-dark-and-grey-mode-card-ui/">Skeleton Screen Gleam Animation</a></figcaption></figure><p>Meaning one process, for example, a state update can start and pause at any time to continue another process or make both happen simultaneously, versus previously in React we had <strong>Block Rendering, </strong>enabling it to only handle one task at a time.</p><p>To understand how to make use of this concept, we have to first get the problem it solves.</p><h4>The Problem Concurrency Solves</h4><p>Stop and continue processes based on the NEED, and not based on times set in debounce or other events to finish to start computing when computing can be done in the background when other events progress. This makes the app more responsive.</p><p>Why we need to debounce or throttle in the first place?</p><p>Let’s say we have a search bar, where users can type in and filter data. If we make updates to the list on every key stroke, then the component would get re-loaded(making it slower) and we would have to make computations(an API call or filtering on the client side) on every version of the text input that user enters. For example, if a user puts ‘s’ we have to make a search on ‘s’ and by the time they have entered ‘se’ we might not be finished with getting results for the ‘s’ so after waiting for those results we will fetch new ones, eventually leading to delayed update of the results. Here’s an example, where the data is fetched from the API on everytext update and by the time this text is clear, the app is still processing results for the previous states and delivering the final results after it’s done with all state updates consecutively:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*B1YFL20km_3TpXnCAIjnGQ.gif" /><figcaption>Crypto Coins Search using <a href="https://www.coingecko.com/">CoinGecko</a> API</figcaption></figure><p>To make this experience faster, we would have used debounce or throttle, but they also introduce the slowness, because we artificially set an arbitrary amount of time to wait or the time needed to wait for the event, for example, the user waiting to finish typing, but then this means that the application is not that responsive while they are typing since results are not getting updated, the benefit of this approach is that our code runs less calculations and thus the results for the final state are delivered more abruptly. As you can see in this example, where the app skips calling API multiple times and only calls after the delay time that is set has passed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*LqddoPMXw0A3kyLdEyhmng.gif" /><figcaption><a href="https://codesandbox.io/s/search-bar-6w1dx8?file=/src/App.js">CodeSandbox URL</a></figcaption></figure><p>But if we interrupted the calculation of the results for the previous state when we received the new state, then we would have a much smoother user experience. So to improve it, we need to determine which processes can be interrupted and which not. In other words, which are the urgent and less-urgent updates. That is where transitions come in.</p><h4>Transitions</h4><p><strong>Urgent updates</strong>: typing, clicking, selecting</p><p><strong>Transition updates</strong>: list update, tab content switch, more data load</p><p>Urgent updates should be happening immediately when user starts typing the input should get updated, the button should get focused on click and etc. Transition updates are ones that take more time and can be interrupted thus they will go into the concurrent rendering.</p><p>We declare what can be considered as a transition by wrapping it in the startTransition and rest of the changes can just be triggered as we used to do it previously.</p><pre>import {startTransition} from &#39;react&#39;;<br><br>// Urgent: Show what was typed<br>setInputValue(input);<br><br>// Mark any state updates inside as transitions<br>startTransition(() =&gt; {<br>  // Transition: Show the results<br>  setSearchQuery(input);<br>});</pre><p>We can also get the state of the transition, whether or not it is pending. The biggest use of this is displaying spinner in the UI. We can do this by using useTransition the hook:</p><pre>const [isPending, startTransition] = useTransition();</pre><p>References:</p><p><a href="https://reactjs.org/docs/hooks-reference.html#usetransition">Hooks API Reference - React</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc5db22a816c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>