<?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 Shruti Latthe on Medium]]></title>
        <description><![CDATA[Stories by Shruti Latthe on Medium]]></description>
        <link>https://medium.com/@shruti.latthe?source=rss-7fccdee124a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VMZW5HXiURjo1bTO7MCU8Q.jpeg</url>
            <title>Stories by Shruti Latthe on Medium</title>
            <link>https://medium.com/@shruti.latthe?source=rss-7fccdee124a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 21:17:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shruti.latthe/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[JavaScript Event Loop: Understanding setTimeout and API Calls]]></title>
            <link>https://medium.com/@shruti.latthe/javascript-event-loop-understanding-settimeout-and-api-calls-478562e79c5e?source=rss-7fccdee124a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/478562e79c5e</guid>
            <category><![CDATA[settimeout]]></category>
            <dc:creator><![CDATA[Shruti Latthe]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 07:01:30 GMT</pubDate>
            <atom:updated>2026-09-08T07:01:30.254Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vD6-M9FlIgagaoxszZwbFw.png" /></figure><p>One of the most common JavaScript interview questions is:</p><blockquote><em>If I have a </em><em>console.log, a </em><em>setTimeout, and an API call, what will execute first?</em></blockquote><p>To answer this correctly, we need to understand three things:</p><ul><li>The <strong>Call Stack</strong></li><li>The <strong>Web APIs</strong></li><li>The <strong>Event Loop and its queues</strong></li></ul><p>Let’s understand them with a simple example.</p><h3>The Example</h3><p>Consider this code:</p><pre>console.log(&quot;A&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;B&quot;);<br>}, 0);<br><br>fetch(&quot;/api/data&quot;)<br>  .then(() =&gt; {<br>    console.log(&quot;C&quot;);<br>  });<br><br>console.log(&quot;D&quot;);</pre><p>What will be printed?</p><p>There are two possible results:</p><pre>ADBC</pre><p>OR</p><pre>ADCB</pre><h3>But why?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYry7FMbDTNmsLkWQSd8tA.png" /></figure><h3>Conclusion:</h3><p>JavaScript doesn’t wait for asynchronous operations like setTimeout() or API calls. The browser handles these operations through Web APIs, while JavaScript continues executing synchronous code.</p><p><strong>In our example:</strong></p><pre>console.log(&quot;A&quot;);<br><br>setTimeout(() =&gt; console.log(&quot;B&quot;), 0);<br><br>fetch(&quot;/api&quot;).then(() =&gt; console.log(&quot;C&quot;));<br><br>console.log(&quot;D&quot;);</pre><p>A and D always execute first. After that, the order of B and C depends on when the timer and API response become ready, along with the Event Loop’s queue priorities.</p><p><strong>The key idea to remember is:</strong></p><blockquote><em>Synchronous code runs first, Promise callbacks use the Microtask Queue, and timer callbacks use the Task Queue. Microtasks are processed before the next task.</em></blockquote><p>Once you understand Call Stack → Web APIs → Queues → Event Loop, asynchronous JavaScript becomes much easier to reason about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=478562e79c5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Inside the JavaScript Engine: From Parsing to Execution (AST, JIT, and V8 Architecture)]]></title>
            <link>https://medium.com/@shruti.latthe/inside-the-javascript-engine-from-parsing-to-execution-ast-jit-and-v8-architecture-72e54006e0bd?source=rss-7fccdee124a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/72e54006e0bd</guid>
            <dc:creator><![CDATA[Shruti Latthe]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 07:03:19 GMT</pubDate>
            <atom:updated>2025-11-06T07:03:19.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upyCAagPr6X0H1dwPEVe3A.png" /></figure><p>When you write JavaScript like this:</p><pre>const sum = (a, b) =&gt; a + b;<br>console.log(sum(2, 3));</pre><p>…it looks simple. But under the hood, your JavaScript engine (like <strong>V8</strong> in Chrome or <strong>SpiderMonkey</strong> in Firefox) performs a fascinating sequence of steps to turn your code into optimized machine instructions.</p><p>Let’s dive into how JavaScript engines — especially <strong>V8</strong> — parse, compile, and execute your code efficiently.</p><h3>⚙️ 1. What Is a JavaScript Engine?</h3><p>A <strong>JavaScript engine</strong> is a program that reads, compiles, and executes JS code.<br> Some popular engines include:</p><ul><li>🧩 <strong>V8</strong> — Chrome, Node.js</li><li>🦊 <strong>SpiderMonkey</strong> — Firefox</li><li>🍎 <strong>JavaScriptCore (Nitro)</strong> — Safari</li></ul><p>Every engine performs three main tasks:</p><ol><li><strong>Parsing</strong> your source code</li><li><strong>Compiling</strong> it to executable form</li><li><strong>Executing</strong> and optimizing it</li></ol><h3>🧩 2. Parsing: Turning Code into a Structure</h3><p>The engine first needs to understand your code before executing it.</p><h3>🔹 Step 1: Tokenization</h3><p>Your code is broken into small pieces called <strong>tokens</strong> — identifiers, operators, literals, etc.<br> Example:</p><pre>let total = 5 + 10;<br>Tokens: let, total, =, 5, +, 10, ;</pre><h3>🔹 Step 2: Syntax Analysis → AST (Abstract Syntax Tree)</h3><p>The tokens are structured into an <strong>Abstract Syntax Tree</strong>, a hierarchical representation of the program.</p><p>Simplified AST:</p><pre>VariableDeclaration<br>└── Identifier (total)<br>    └── BinaryExpression (+)<br>        ├── Literal (5)<br>        └── Literal (10)</pre><p>This <strong>AST</strong> is used by later stages (interpreter and compiler) to generate executable code.</p><h3>⚡ 3. The Interpreter: Ignition</h3><p>Once the AST is ready, V8 passes it to <strong>Ignition</strong>, its <strong>interpreter</strong>.</p><ul><li>Ignition converts the AST into <strong>bytecode</strong>, a low-level, compact representation of your program.</li><li>This bytecode can be executed directly by the virtual machine.</li></ul><p>🌀 <strong>Goal:</strong> Start execution as quickly as possible.<br> It’s like “running immediately” rather than waiting for a full compilation.</p><p>But bytecode isn’t the fastest format for execution — that’s where V8’s <strong>compiler</strong> steps in.</p><h3>🚀 4. The Compiler: TurboFan</h3><p>V8 uses <strong>TurboFan</strong> — a highly optimized <strong>JIT (Just-In-Time)</strong> compiler — to speed up frequently executed code.</p><p>Here’s how:</p><ol><li>Ignition runs the bytecode and profiles performance.</li><li>When it detects “hot” functions (executed many times), it sends them to TurboFan.</li><li>TurboFan compiles them into <strong>highly optimized machine code</strong> for your CPU.</li><li>If assumptions (like data types) change later, V8 <strong>de-optimizes</strong> back to bytecode.</li></ol><p>This dynamic process lets V8 balance:</p><ul><li><strong>Fast startup</strong> (via interpreter)</li><li><strong>High performance</strong> (via compiler)</li></ul><h3>🧠 5. V8 Engine Architecture</h3><p>Let’s visualize how V8 is structured internally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18KDl4pCjbW7DIlFyQ6BIw.png" /></figure><pre>             ┌──────────────────────────┐<br>             │      JavaScript Code      │<br>             └────────────┬──────────────┘<br>                          ↓<br>                  ┌─────────────┐<br>                  │    Parser    │<br>                  └──────┬──────┘<br>                         ↓<br>               ┌─────────────────┐<br>               │  Abstract Syntax │<br>               │      Tree (AST)  │<br>               └──────┬───────────┘<br>                      ↓<br>           ┌────────────────────┐<br>           │    Ignition (Interpreter) │<br>           │    → Generates Bytecode   │<br>           └──────────┬───────────────┘<br>                      ↓<br>           ┌────────────────────┐<br>           │   TurboFan (JIT Compiler) │<br>           │   → Optimized Machine Code │<br>           └──────────┬───────────────┘<br>                      ↓<br>              🚀 Execution on CPU</pre><h3>🔍 Key Components of V8:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZgOpkz6ToJvTXtpl_BsNtw.png" /></figure><h3>🧮 6. JIT (Just-In-Time) Compilation Explained</h3><p>Traditional compilers (like in C++) compile everything <em>before execution</em>.<br> But <strong>JIT compilation</strong> happens <em>during</em> runtime — hence “Just In Time”.</p><h3>🔹 Advantages of JIT</h3><ul><li>Learns from real execution (types, patterns)</li><li>Optimizes only what’s needed</li><li>Adapts dynamically to runtime changes</li></ul><h3>🔹 De-optimization</h3><p>If the JIT compiler made assumptions that later turn out false (like variable types changing), it can revert that part of code to the interpreter — ensuring correctness.</p><h3>🔁 7. Interpreter vs Compiler: A Quick Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFn75qUcchi9AfyIAqMfrw.png" /></figure><h3>🧠 8. Memory Management in V8</h3><p>V8 also handles <strong>memory allocation and garbage collection</strong> efficiently.</p><ul><li>Uses <strong>generational garbage collection</strong>:</li><li><strong>New Space:</strong> Short-lived objects</li><li><strong>Old Space:</strong> Long-lived objects</li><li>Background threads run <strong>incremental and concurrent</strong> GC to avoid blocking the main thread.</li></ul><p>This ensures smooth execution even for large apps.</p><h3>🔧 9. Full Flow of Execution</h3><p>Here’s the big picture of how your code runs in V8:</p><pre>JavaScript Source Code<br>       ↓<br>Tokenization → AST<br>       ↓<br>Ignition → Bytecode<br>       ↓<br>Profiler → Detect Hot Code<br>       ↓<br>TurboFan → Optimized Machine Code<br>       ↓<br>Execution + Garbage Collection</pre><h3>💡 10. Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sy4GPPiH0KGn2NezTeByMw.png" /></figure><h3>🚀 Final Thoughts</h3><p>Modern JavaScript engines like <strong>V8</strong> are marvels of engineering — blending <strong>interpreters, compilers, and JIT optimizations</strong> to make JS both fast and flexible.</p><p>Every time your browser executes JavaScript instantly, you’re seeing:</p><ul><li><strong>Parsing</strong> via AST</li><li><strong>Interpretation</strong> via Ignition</li><li><strong>Optimization</strong> via TurboFan</li><li><strong>Memory management</strong> via Orinoco</li></ul><p>That’s how your simple console.log(&quot;Hello World&quot;) becomes a high-performance machine instruction in milliseconds ⚡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72e54006e0bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React Outlet: A Comprehensive Guide]]></title>
            <link>https://medium.com/@shruti.latthe/understanding-react-outlet-a-comprehensive-guide-b122b1e5e7ff?source=rss-7fccdee124a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b122b1e5e7ff</guid>
            <category><![CDATA[react-outlet]]></category>
            <category><![CDATA[react-router-dom]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[outlet]]></category>
            <dc:creator><![CDATA[Shruti Latthe]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 04:07:02 GMT</pubDate>
            <atom:updated>2024-03-01T04:07:02.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LM_lygm0NqPLp2AD" /></figure><p>React is a powerful JavaScript library for building user interfaces. One of its key features is React Router, which allows developers to create dynamic, single-page applications with multiple views. In this blog post, we’ll explore React Outlet, an essential part of React Router, and understand its role in managing nested routes within a React application.</p><p><strong>What is React Outlet?</strong></p><p>React Outlet is a component provided by React Router that serves as a placeholder for child routes within a parent route. It allows for the nesting of routes, enabling developers to create complex navigation structures in their applications.</p><pre>import React from &quot;react&quot;;<br><br>// import components<br>import Routes from &quot;./routes&quot;;<br><br>// component<br>const App = () =&gt; {<br>  return (<br>    &lt;&gt;<br>   <br>      &lt;Routes /&gt;<br>    &lt;/&gt;<br>  );<br>};<br>export default App;</pre><pre>// import packages<br><br>import { BrowserRouter, Outlet, Route, Routes } from &quot;react-router-dom&quot;;<br>import React, { Suspense, lazy } from &quot;react&quot;;<br>import {<br>  dashboard,<br>  homePath,<br>  loginPath,<br>  rootPath<br>} from &quot;./routePaths&quot;;<br><br>import Loader from &quot;../components/loader&quot;;<br>import ProtectedRoute from &quot;./protectedRoute&quot;;<br><br>// import route paths<br><br>const Login = lazy(() =&gt; import(&quot;../pages/login&quot;));<br>const Home = lazy(() =&gt; import(&quot;../pages/home&quot;));<br>const RouteNotFound = lazy(() =&gt; import(&quot;../pages/pageNotFound&quot;));<br><br>const DashboardComponent = lazy(() =&gt; import(&quot;../pages/dashboard/&quot;));<br><br><br><br>const AllRoutes = () =&gt; {<br>  return (<br>    &lt;Suspense fallback={&lt;Loader /&gt;}&gt;<br>      &lt;BrowserRouter&gt;<br>        &lt;Routes&gt;<br>          &lt;Route path={rootPath} element={&lt;Outlet /&gt;}&gt;//--------------gives access to child component<br>            &lt;Route index element={&lt;Login /&gt;} /&gt;  //------------showing / route component<br>            &lt;Route path={loginPath} element={&lt;Login /&gt;} /&gt;<br>            {/* &lt;Route path={accessErrorPage} element={&lt;AccessErrorPage /&gt;} /&gt; */}<br>            &lt;Route element={&lt;ProtectedRoute /&gt;}&gt;<br>              &lt;Route path={homePath} element={&lt;Home /&gt;} /&gt;<br>              &lt;Route path={dashboard} element={&lt;DashboardComponent /&gt;} /&gt;<br>            &lt;/Route&gt;<br>            &lt;Route path=&quot;*&quot; element={&lt;RouteNotFound /&gt;} /&gt;<br>          &lt;/Route&gt;<br>        &lt;/Routes&gt;<br>      &lt;/BrowserRouter&gt;<br>    &lt;/Suspense&gt;<br>  );<br>};<br><br>export default AllRoutes;<br></pre><ol><li>App Component:</li></ol><ul><li>The App component is the entry point of our React application.</li><li>It renders the Routes component, which handles the routing of our application.</li></ul><p>2.AllRoutes Component:</p><ul><li>The AllRoutes component sets up the routes for our application using React Router.</li><li>It defines routes for different paths and lazy-loads components using the Suspense component for better performance.</li><li>Inside the routes, it utilizes the Outlet component to handle nested routes.</li></ul><p><strong>All in All</strong></p><ol><li>Imports: we are importing necessary components and functions from react-router-dom, as well as other components and route paths from your project.</li><li>Lazy Loading: we are using lazy() from React to lazily load components. This improves initial load time by splitting the bundle into smaller chunks that are loaded on demand.</li><li>Suspense: we are using the &lt;Suspense&gt; component to wrap your lazy-loaded routes. This allows you to specify a fallback UI while the components are loading.</li><li>Routing: Inside your &lt;Routes&gt; component, we are defining different routes using the &lt;Route&gt; component. Here&#39;s a breakdown of the routes:</li></ol><ul><li>Root Route (/): This route is for the root path of our application. It renders the Login component.</li><li>Login Route (/login): This route renders the Login component.</li></ul><p>5. Protected Routes: These routes are wrapped inside a &lt;ProtectedRoute&gt; component. This likely handles authentication logic to restrict access to certain routes. Inside the protected routes, you have:</p><ul><li>Home Route (/home): Renders the Home component.</li><li>Dashboard Route (/dashboard): Renders the DashboardComponent component.</li><li>Wildcard Route (*): This route matches any path that doesn&#39;t match the previous routes and renders the RouteNotFound component.</li></ul><p>6. BrowserRouter: This component provides the routing functionality to your application. It uses HTML5 history API to keep your UI in sync with the URL.</p><pre>// import packages<br>import React, { useEffect } from &quot;react&quot;;<br>import { useNavigate, Outlet } from &quot;react-router-dom&quot;;<br><br>import BaseLayout from &quot;../pages/layout&quot;;<br><br>// import route paths<br>import { rootPath } from &quot;./routePaths&quot;;<br><br>// component<br>const ProtectedRoute = () =&gt; {<br>  const navigate = useNavigate();();<br>  const isAuthenticated = false; //add a dynamic method call<br>  const user = &#39;shruti&#39;;//add a dynamic method call<br><br>  useEffect(() =&gt; {<br>    if (!isAuthenticated) {<br>      return navigate(rootPath, { replace: true });<br>    }<br>  }, [isAuthenticated, navigate]);<br><br>  return (<br>    &lt;BaseLayout &gt;<br>      &lt;Outlet /&gt;<br>    &lt;/BaseLayout&gt;<br>  );<br>};<br><br>export default ProtectedRoute;</pre><p><strong>ProtectedRoute Component:</strong></p><ul><li>The ProtectedRoute component is responsible for protecting certain routes that require authentication.</li><li>It utilizes the Outlet component to render nested child routes within the protected route.</li></ul><pre>import React, { lazy } from &quot;react&quot;;<br><br>import ErrorBoundary from &quot;../../components/error-boundary&quot;;<br><br>// const Header = lazy(() =&gt; import(&quot;@components/header&quot;));<br>const Sidebar = lazy(() =&gt; import(&quot;../../components/sidebar&quot;));<br>export default function BaseLayout(props) {<br>  const { children } = props;<br>  // common things we need to show on each page like Header,sidebar ,Footer<br>  return (<br>    &lt;ErrorBoundary&gt;<br>      &lt;div className=&quot;wrapper&quot;&gt;<br>        &lt;div className=&quot;d-flex position-relative&quot;&gt;<br>          &lt;Sidebar /&gt;<br>          &lt;main className=&quot;main-container&quot;&gt;<br>            {/* &lt;Header /&gt; */}<br>            {children}//components from all routes<br>          &lt;/main&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/ErrorBoundary&gt;<br>  );<br>}<br><br>BaseLayout.defaultProps = {<br>  children: [],<br>  user: {},<br>};</pre><p><strong>BaseLayout Component:</strong></p><ul><li>The BaseLayout component serves as a common layout structure for all pages in our application.</li><li>It contains common elements like a sidebar and main content area.</li><li>Child components from different routes are rendered using the Outlet component within the main content area.</li></ul><p><strong>Understanding React Outlet:</strong></p><ul><li>React Outlet is used within the AllRoutes component to render child routes within a parent route.</li><li>It allows for the modularization of routes, making it easier to manage complex navigation structures.</li><li>Nested routes can have their own layouts and functionality while still being part of a larger parent route.</li><li>By using React Outlet, developers can create more organized and maintainable codebases for their React applications.</li></ul><p><strong>Conclusion:<br></strong>React Outlet is a powerful tool provided by React Router for managing nested routes within a React application. By understanding its usage and incorporating it into our routing setup, we can create more dynamic and flexible user interfaces. Whether it’s protecting routes, creating layouts, or handling complex navigation structures, React Outlet plays a crucial role in building robust React applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b122b1e5e7ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Git Rebase: A User-Friendly Guide]]></title>
            <link>https://medium.com/@shruti.latthe/understanding-git-rebase-a-user-friendly-guide-0e810200725a?source=rss-7fccdee124a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e810200725a</guid>
            <category><![CDATA[commands]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[git-rebase]]></category>
            <dc:creator><![CDATA[Shruti Latthe]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 02:41:48 GMT</pubDate>
            <atom:updated>2024-02-21T02:41:48.550Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ail2JVtGD6vHEHfU9FazAQ.jpeg" /></figure><p>Git is an incredibly powerful tool for managing your codebase, but it can sometimes feel overwhelming, especially for beginners. One Git command that often causes confusion is git rebase. In this guide, we&#39;ll break down what Git rebase is, why it&#39;s useful, and how you can use it in your workflow.</p><h3>What is Git Rebase?</h3><p>In simple terms, Git rebase is a command used to rewrite commit history. When you rebase, you’re essentially changing the base of your branch. Instead of merging changes directly, like with git merge, rebase integrates changes by moving each of your commits to the tip of the branch you&#39;re rebasing onto</p><h3>Why Use Git Rebase?</h3><h3>1. Cleaner Commit History</h3><p>One of the main benefits of using rebase is that it allows you to maintain a cleaner commit history. By moving your commits to the tip of the branch, you can create a linear history, making it easier to understand the evolution of your codebase.</p><h3>2. Avoiding Merge Commits</h3><p>Unlike git merge, which creates a merge commit to integrate changes from one branch into another, rebase incorporates changes by replaying each commit on top of the branch you&#39;re rebasing onto. This can result in a cleaner, more linear history without unnecessary merge commits cluttering up your timeline.</p><h3>3. Resolving Merge Conflicts</h3><p>Rebasing can also help simplify the process of resolving merge conflicts. By rebasing your changes onto the latest version of the branch you’re targeting, you can address conflicts as they arise, one commit at a time. This can make conflict resolution more manageable and reduce the risk of conflicts snowballing into larger issues.</p><h3>How to Use Git Rebase</h3><p>Now that we understand why rebasing can be useful, let’s walk through how to use it in practice.</p><h3>1. Start by Fetching Latest Changes</h3><p>Before you rebase your branch, it’s a good idea to fetch the latest changes from the remote repository to ensure you’re working with the most up-to-date code.</p><pre>git fetch<br>git pull</pre><h3>2. Checkout the Branch You Want to Rebase</h3><p>Next, switch to the branch you want to rebase. For example, if you’re working on a feature branch called my-feature, you would use the following command:</p><pre>git checkout my-feature</pre><h3>3. Rebase Onto the Target Branch</h3><p>Once you’re on the branch you want to rebase, use the git rebase command followed by the name of the branch you want to rebase onto. For example, if you want to rebase your changes onto the main branch, you would run:</p><pre>git rebase main</pre><h3>4. Resolve any Merge Conflicts</h3><p>During the rebase process, Git may encounter merge conflicts that need to be resolved manually. If this happens, Git will pause the rebase and prompt you to resolve the conflicts in each affected file. see the commits list and exit using :wq ,resolve all merge conflicts &amp;stage all changes</p><p>Once you’ve resolved the conflicts, you can continue the rebase by running:</p><pre>git rebase --continue</pre><p>resolve all merge conflict and keep continue process(git rebase — continue) till all merge conflict get resolved.</p><h3>5. Push the Rebased Branch</h3><p>Once you’ve finished rebasing your branch and resolved any conflicts, you can push your changes to the remote repository. Depending on your workflow, you may need to force push if you’ve rewritten history with the rebase.</p><pre>git push --force</pre><p>if you wish to exit from flow any time <strong>(git rebase — abort )</strong> this command will bring you to normal stag.</p><h3><strong>In Short :</strong></h3><ul><li>branch develop latest pull</li><li>branch intermidiate latest pull</li><li>checkout intermidiate</li><li>remove all changes or stash</li><li>git rebase develop (hit this command)</li><li>see the commits list and exit using :wq<br>resolve all merge conflicts stage all changes</li><li>git rebase — continue <br>resolve all merge conflict and keep continue process(git rebase — continue) till all merge conflict get resolved</li><li>once all good then push your intermediate branch<br>git push — force</li><li>if you wish to exit from flow any time (git rebase — abort ) this command will bring you to normal stag.</li></ul><h3><strong>Conclusion</strong></h3><p><strong>Git rebase </strong>is a powerful tool for managing your commit history and integrating changes from one branch into another. By understanding how rebase works and following best practices, you can maintain a cleaner, more streamlined codebase and avoid unnecessary merge commits.</p><p>Next time you find yourself in a situation where you need to incorporate changes from one branch into another, consider using git rebase to keep your commit history tidy and your workflow efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e810200725a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Centralized API Client File in React with Axios]]></title>
            <link>https://medium.com/@shruti.latthe/creating-a-centralized-api-client-file-in-react-with-axios-5e69dc27fdb1?source=rss-7fccdee124a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e69dc27fdb1</guid>
            <category><![CDATA[axios-react]]></category>
            <category><![CDATA[files]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[axioscreate]]></category>
            <dc:creator><![CDATA[Shruti Latthe]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 16:51:22 GMT</pubDate>
            <atom:updated>2024-11-11T10:59:12.494Z</atom:updated>
            <content:encoded><![CDATA[<p>When building React applications that interact with APIs, it’s essential to maintain a clean and organized approach to handle API calls. One effective way to achieve this is by creating<strong> a centralized API client file</strong>. In this tutorial, we’ll explore how to structure such a file using Axios, a popular HTTP client for making request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eeny_KrL_JO0wcd4oBgmxA.jpeg" /></figure><h3>Why Centralize API Calls?</h3><p>Centralizing API calls offers several benefits:</p><ol><li>Modularity: Separating API logic into a single file promotes modularity and reusability across your application.</li><li>Organization: All API-related code is contained within a single file, making it easier to manage and maintain.</li><li>Consistency: By defining common configurations and error handling strategies in one place, you ensure consistency throughout your application.</li></ol><h3>Setting Up Axios</h3><p>First, ensure you have Axios installed in your project. You can install it via npm or yarn:</p><pre>npm install axios<br># or<br>yarn add axios</pre><h3>Creating the API Client File</h3><p>Let’s create a file named apiClient.js to handle our API calls:</p><pre>// apiClient.js<br><br>import axios from &#39;axios&#39;;<br><br>const BASE_URL = process.env.REACT_APP_BASE_URL || &#39;https://api.example.com&#39;;<br><br>const apiClient = axios.create({<br>  baseURL: BASE_URL,<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    // You can add other headers like authorization token here<br>  },<br>});<br><br>// Define common API methods<br>const _get = (url, config = {}) =&gt; {<br>  return apiClient.get(url, config);<br>};<br><br>const _delete = (url, config = {}) =&gt; {<br>  return apiClient.delete(url, config);<br>};<br><br>const _put = (url, data = {}, config = {}) =&gt; {<br>  return apiClient.put(url, data, config);<br>};<br><br>const _post = (url, data = {}, config = {}) =&gt; {<br>  return apiClient.post(url, data, config);<br>};<br><br>// Export API methods<br>export { _get, _delete, _put, _post };</pre><p>In above file:</p><ul><li>We create an Axios instance with a base URL and default headers.</li><li>We define various API functions corresponding to different endpoints.</li></ul><p>Set up Environment Variables: First, you need to set up environment variables for your different environments. You can typically do this by creating .env files for each environment. For example:</p><ul><li>.env.development: Contains variables for the development environment.</li><li>.env.qa: Contains variables for the QA environment.</li><li>.env.staging: Contains variables for the staging environment.</li><li>.env.production: Contains variables for the production environment.</li></ul><p>Inside each .env file, define your base URL:</p><p><strong>REACT_APP_BASE_URL=</strong><a href="https://api.example.com/"><strong>https://api.example.com</strong></a></p><ol><li><strong>Accessing Different Environments</strong>: Depending on your environment (e.g., development, QA, staging), React will automatically load the corresponding .env file, and the BASE_URL will be set accordingly.</li></ol><p>For example, during development, React will load .env.development, and BASE_URL will be set to the value specified in that file.</p><p>Similarly, in other environments (e.g., QA, staging), React will load the respective .env file.</p><p>2. <strong>Usage in React Components</strong>: You can continue to use the api object in your React components as shown in the previous example. The base URL will be dynamically determined based on the environment.</p><p>This setup allows you to manage different base URLs for different environments easily, ensuring that your React application communicates with the appropriate backend depending on the environment it’s running in.</p><h3>Using the API Client in Components</h3><p>Now, let’s see how to use this API client in a React component:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br>import { _get, _post, _put, _delete } from &#39;./apiClient&#39;; // Adjust the path as needed<br><br>function ExampleComponent() {<br>  const [data, setData] = useState([]);<br><br>  useEffect(() =&gt; {<br>    // Fetch data when component mounts<br>    fetchData();<br>  }, []);<br><br>  const fetchData = async () =&gt; {<br>    try {<br>      const response = await _get(&#39;/data&#39;, { headers: { Authorization: &#39;Bearer your_token_here&#39; } });<br>      setData(response.data);<br>    } catch (error) {<br>      console.error(&#39;Error fetching data:&#39;, error);<br>      // Handle errors<br>    }<br>  };<br><br>  const addData = async () =&gt; {<br>    try {<br>      const newData = { name: &#39;New Item&#39; };<br>      await _post(&#39;/data&#39;, newData);<br>      fetchData(); // Refresh data after adding<br>    } catch (error) {<br>      console.error(&#39;Error adding data:&#39;, error);<br>      // Handle errors<br>    }<br>  };<br><br>  const updateData = async (id, updatedData) =&gt; {<br>    try {<br>      await _put(`/data/${id}`, updatedData);<br>      fetchData(); // Refresh data after updating<br>    } catch (error) {<br>      console.error(&#39;Error updating data:&#39;, error);<br>      // Handle errors<br>    }<br>  };<br><br>  const deleteData = async (id) =&gt; {<br>    try {<br>      await _delete(`/data/${id}`);<br>      fetchData(); // Refresh data after deleting<br>    } catch (error) {<br>      console.error(&#39;Error deleting data:&#39;, error);<br>      // Handle errors<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Example Component&lt;/h1&gt;<br>      &lt;button onClick={addData}&gt;Add Data&lt;/button&gt;<br>      &lt;ul&gt;<br>        {data.map(item =&gt; (<br>          &lt;li key={item.id}&gt;<br>            {item.name}<br>            &lt;button onClick={() =&gt; updateData(item.id, { name: &#39;Updated Item&#39; })}&gt;Update&lt;/button&gt;<br>            &lt;button onClick={() =&gt; deleteData(item.id)}&gt;Delete&lt;/button&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ExampleComponent;</pre><p>In Axios, the config parameter allows you to pass additional configurations for the HTTP request. Some common configurations include headers, query parameters, request timeout, authentication tokens.</p><p><strong>Note: </strong>When creating the Axios instance with axios.create(), the baseURL option is set to BASE_URL. This means that all requests made with this Axios instance will have the base URL prefixed to their URLs.</p><p>For example, if you call _get(&#39;/data&#39;) from your ExampleComponent, Axios will send a GET request to &#39;https://api.example.com/data&#39;</p><h3>Conclusion</h3><p>Centralizing API calls in a React application using Axios provides a clean and organized approach to managing API logic. By creating a centralized API client file, you can achieve modularity, organization, and consistency in your codebase. This approach simplifies maintenance and promotes code reuse across your application.</p><p>Start organizing your API calls today and experience the benefits it brings to your React projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e69dc27fdb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React UseReducer Hook]]></title>
            <link>https://medium.com/@shruti.latthe/react-usereducer-hook-843d0ea0ef24?source=rss-7fccdee124a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/843d0ea0ef24</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <dc:creator><![CDATA[Shruti Latthe]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 10:25:40 GMT</pubDate>
            <atom:updated>2024-01-30T10:26:11.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*gYag5SZiCIE-0wt9iq8zGw@2x.jpeg" /></figure><p><strong>What is useState in React?</strong></p><p>useState is a compelling Hook for simplifying managing states in our React Application. In useState definition of the setter function is <strong>hidden</strong></p><p><strong>What is setter function in usestate?</strong></p><p>In React’s useState, the setter function is a function that allows you to update the state value. It’s typically named with a convention like setVariable, where “Variable” is the state variable name. When you call this function with a new value, React re-renders the component with the updated state.</p><p><strong>For example</strong></p><pre>const [count, setCount] = useState(0);<br><br>// Later in the code, to update the &#39;count&#39; state:<br>setCount(count + 1);</pre><p>This ensures that you’re not directly modifying the state variable but instead using the provided function for state updates, which helps React manage state changes more effectively.</p><p><strong>What is useReducer in React?</strong></p><p>useReducer Hooks is used to storing and updating states just like useState Hook but in useReducer definition of the setter function is built custom as will explain in a bit.</p><p>useReducer is another React Hook that is used for managing state, especially when the state logic is more complex. It’s an alternative to useState, but it involves creating a custom reducer function.</p><p>In useReducer, the state is updated based on an action and a dispatch function is used to trigger the state updates.</p><p>The reducer function takes the current state and an action, and returns the new state. This can be useful for handling more intricate state logic and transitions.</p><p><strong>Here’s a brief example:</strong></p><pre>const initialState = { count: 0 };<br><br>function reducer(state, action) {<br>  switch (action.type) {<br>    case &#39;increment&#39;:<br>      return { count: state.count + 1 };<br>    case &#39;decrement&#39;:<br>      return { count: state.count - 1 };<br>    default:<br>      return state;<br>  }<br>}<br><br>const [state, dispatch] = useReducer(reducer, initialState);<br><br>// Later in the code, to update the state using dispatch:<br>dispatch({ type: &#39;increment&#39; });</pre><p>In this example, dispatch is the custom setter function, and it takes an action object with a defined type property to specify the kind of state update to perform.</p><p>useReducer is able to update multiple types of data using a switch statement similarly we can use as many as we can to handle different types of data so we can now handle the functionality of multiple useState with just single useReducer.</p><p>Also, we can separate the above reducer function into a separate file to share this logic between multiple components this makes useReducer more powerful compared to useState.</p><p><strong>Conclusion</strong> : useReducer reduce the need for multiple instances of useState by enabling the same functionality to be achieved with just one useReducer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=843d0ea0ef24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner developer Common mistake while working with the React map function]]></title>
            <link>https://medium.com/@shruti.latthe/beginner-developer-common-mistake-while-working-with-the-react-map-function-2b085ed25c7b?source=rss-7fccdee124a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b085ed25c7b</guid>
            <category><![CDATA[jsx]]></category>
            <category><![CDATA[map-function]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Shruti Latthe]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 10:27:57 GMT</pubDate>
            <atom:updated>2023-09-30T10:27:57.442Z</atom:updated>
            <content:encoded><![CDATA[<p>Beginner developer Common mistake while working with the React map function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cUwQii4YTk7wWnsV" /></figure><pre>myArray1.map((item) =&gt;{ &lt;p&gt;{item}&lt;/p&gt;})</pre><pre>myArray2.map((item) =&gt;( &lt;p&gt;{item}&lt;/p&gt;))</pre><p><strong>Que.</strong> What is the difference between the above two map functions?</p><p><strong>Answer:<br></strong>The two code snippets I have provided are examples of using the map function in <strong>JavaScript </strong>to transform elements of an array. However, there is a difference between the two in terms of how they handle the<strong> JSX syntax</strong>.</p><p>1.</p><pre>myArray.map((item) =&gt; { &lt;p&gt;{item}&lt;/p&gt; })</pre><p>In this snippet, I’m using curly braces {} inside the arrow function, but I haven&#39;t specified a return statement. This means that the code inside the curly braces is treated as a block of JavaScript code, and there&#39;s no explicit return value. This won&#39;t work as expected when you&#39;re trying to render JSX.</p><p>To fix this, you should use parentheses () instead of curly braces {} and include a return statement to return the JSX element: Like the below snippet</p><pre>myArray.map((item) =&gt; { return &lt;p&gt;{item}&lt;/p&gt; })</pre><p>2.</p><pre>myArray2.map((item) =&gt; ( &lt;p&gt;{item}&lt;/p&gt; ))</pre><p>In this snippet, I’m using parentheses () around the JSX element inside the arrow function. This tells JavaScript to treat the JSX element as a single expression and implicitly return it. This is the correct way to use the map function with JSX.</p><p>So, the key difference between the two code snippets is the use of parentheses and the presence of a return statement. The second snippet is the correct way to use mapfunction with JSX and it will create an array of JSX elements. The first snippet will not work as intended for rendering JSX.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b085ed25c7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overview of Redux Toolkit]]></title>
            <link>https://medium.com/@shruti.latthe/overview-of-redux-toolkit-eccbbcdbe0cc?source=rss-7fccdee124a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/eccbbcdbe0cc</guid>
            <category><![CDATA[toolkit]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-redux]]></category>
            <dc:creator><![CDATA[Shruti Latthe]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 17:22:48 GMT</pubDate>
            <atom:updated>2023-06-04T17:22:48.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*3PfoP1dKs44n_Q1FtGF_7g.png" /></figure><p><strong>Introduction:</strong> In the world of web development, managing application state efficiently is crucial for creating robust and maintainable code. Redux, a popular state management library for JavaScript applications, provides a reliable solution. However, Redux can be challenging to set up and work with due to its boilerplate code. That’s where Redux Toolkit comes to the rescue. Redux Toolkit is a powerful package that simplifies the process of working with Redux, reducing boilerplate code and enhancing developer productivity. In this blog post, we’ll explore the benefits of Redux Toolkit and learn how to leverage its features effectively.</p><ol><li><strong>What is Redux Toolkit?</strong></li></ol><p>Redux Toolkit is an official package maintained by the Redux team, designed to make Redux more approachable and efficient. It encapsulates best practices and provides a standardized way of working with Redux. The toolkit incorporates essential Redux packages such as Redux DevTools, Redux Thunk, and Redux-observable, making them easier to use out of the box.</p><p><strong>2. Key Features of Redux Toolkit:</strong></p><p>a) Simplified Redux Configuration: Redux Toolkit eliminates the need to write boilerplate code, such as action creators and switch statements, by introducing a set of helper functions. These functions enable you to define actions and reducers in a concise and intuitive manner.</p><p>b) Immutability Made Easy: Immutable state management is crucial for predictable application behavior. Redux Toolkit simplifies this process by leveraging an immutability library called Immer. Immer allows you to write reducers that directly modify the state while maintaining immutability behind the scenes.</p><p>c) Integrated Middleware: Redux Toolkit integrates popular middleware libraries like Redux Thunk and Redux-observable, enabling developers to handle asynchronous actions seamlessly. You can effortlessly dispatch async actions and perform side effects without the need for extra setup.</p><p>d) Redux DevTools Extension: Redux Toolkit comes with built-in support for the Redux DevTools extension, which allows you to inspect and debug your application’s state changes. This tool is invaluable for tracking down bugs and understanding how your state evolves over time.</p><p><strong>3.Redux Toolkit key terms</strong>:</p><p>To begin using Redux Toolkit, follow these steps: a) Install Redux Toolkit using npm or yarn: npm install @reduxjs/toolkit or yarn add @reduxjs/toolkit.</p><p>b) Create a Redux store using the configureStore the function provided by Redux Toolkit.</p><p>c) Define your state, reducers, and actions using the createSlice function. This function generates the action creators and reducer automatically, reducing the amount of boilerplate code you need to write.</p><p>d) Use the generated action creators and reducer in your components to manage the state. By using useSelector and UseDispatch methods</p><p><strong>4.Advanced Features and Beyond:</strong> Redux Toolkit offers additional features such as createAsyncThunk for handling asynchronous actions, createEntityAdapter for managing normalized data structures, and createSlice’s extraReducers option for handling actions from multiple slices. These advanced features allow you to build complex applications while keeping your codebase organized and maintainable.</p><p><strong>Conclusion:</strong></p><p>Redux Toolkit is a game-changer when it comes to state management with Redux. By providing a simplified and opinionated approach, it reduces the complexity and boilerplate code associated with traditional Redux setups. With Redux Toolkit, you can focus more on building your application’s logic and less on managing the state. If you’re starting a new project or considering migrating an existing Redux project, using Redux Toolkit is undoubtedly a wise decision that will enhance your development experience and increase productivity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eccbbcdbe0cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React -login-app with mock API]]></title>
            <link>https://medium.com/@shruti.latthe/react-login-app-with-mock-api-510fcc1a5ff0?source=rss-7fccdee124a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/510fcc1a5ff0</guid>
            <category><![CDATA[logouts]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[functionality]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[login]]></category>
            <dc:creator><![CDATA[Shruti Latthe]]></dc:creator>
            <pubDate>Wed, 04 May 2022 10:59:28 GMT</pubDate>
            <atom:updated>2022-05-04T10:59:28.532Z</atom:updated>
            <content:encoded><![CDATA[<p>hello guys in this article we are looking up for login and logout functional part with your mock-api here, in api section you just have to put your API and do the changes accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*88INLIz_kM5KlL6H7Pe7QQ.png" /></figure><blockquote><strong>Step1: create react app with following command.</strong></blockquote><pre>npx create-react-app login-app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PgVWdpHY4C9q27X1xS4JA.png" /></figure><blockquote><strong>Step 2: open the project and install bootstrap with following command</strong></blockquote><pre>npm i bootstrap</pre><blockquote><strong>Step 3: Then, import bootstrap.min.css from node_modules inside src/App.js file.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pRxGPdHGi1TeVqURUPKjsw.png" /></figure><p>Remove the header content from the app.js</p><blockquote><strong>Step4 : Create React Login and Dashboard Components under components folder</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*bmIHyWe3XKCQm8T7aPI3EA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7LnyhSa8u3chCZqMxbSlMQ.png" /></figure><p>your folder structure looks like this components → Login — -&gt; Login.js and _login.scss</p><blockquote><strong>Step 5: install sass</strong></blockquote><pre>npm i node-sass</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*KoCoFooHRhy0VFWXZLXiJQ.png" /></figure><p>use this extension for sass compiler</p><blockquote><strong>Step 6:Enable Routing in React</strong></blockquote><p>Run the command in the terminal to install react-router-dom module to enable Router service in React.</p><pre>npm install react-router-dom</pre><blockquote><strong>Step 7: Lets do route part now</strong></blockquote><p>Next, import BrowserRouter, Route, SwitchReact router modules to enable the routers with their associative components. Go to src/App.js and include the following code in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*gTVz-knkLlKJMtMR__SnXg.png" /></figure><pre>import &#39;./App.css&#39;;</pre><pre>import &#39;../node_modules/bootstrap/dist/css/bootstrap.min.css&#39;;</pre><pre>import { BrowserRouter, Route, Switch} from &quot;react-router-dom&quot;;</pre><pre>import Dashboard from &#39;./components/Dashboard/Dashboard&#39;;</pre><pre>import Login from &#39;./components/Login/Login&#39;;</pre><pre>function App() {</pre><pre>return (</pre><pre>&lt;div className=&quot;wrapper&quot;&gt;</pre><pre>&lt;BrowserRouter&gt;</pre><pre>&lt;Switch&gt;</pre><pre>&lt;Route path=&quot;/login&quot;&gt;</pre><pre>&lt;Login /&gt;</pre><pre>&lt;/Route&gt;</pre><pre>&lt;Route path=&quot;/dashboard&quot;&gt;</pre><pre>&lt;Dashboard /&gt;</pre><pre>&lt;/Route&gt;</pre><pre>&lt;/Switch&gt;</pre><pre>&lt;/BrowserRouter&gt;</pre><pre>&lt;/div&gt;</pre><pre>);</pre><pre>}</pre><pre>export default App;</pre><p>here in this step we have just defined formal routes we will switch the routers later conditionally.</p><blockquote><strong>Step 8: now we will start designing Login.js page</strong></blockquote><p>here we are using bootstrap class and our custom scss. paste the following code accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*RvEztrGDi9CA39oJ20oZkw.png" /></figure><pre>import React from &quot;react&quot;;</pre><pre>const Login = () =&gt; {</pre><pre>return (</pre><pre>&lt;&gt;</pre><pre>&lt;div class=&quot;card my_login_card&quot; &gt;</pre><pre>&lt;div class=&quot;card-body&quot;&gt;</pre><pre>&lt;form&gt;</pre><pre>&lt;div class=&quot;mb-3&quot;&gt;</pre><pre>&lt;label for=&quot;exampleInputEmail1&quot; class=&quot;form-label&quot;&gt;</pre><pre>Email address</pre><pre>&lt;/label&gt;</pre><pre>&lt;input</pre><pre>type=&quot;email&quot;</pre><pre>class=&quot;form-control&quot;</pre><pre>id=&quot;exampleInputEmail1&quot;</pre><pre>aria-describedby=&quot;emailHelp&quot;</pre><pre>/&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;div class=&quot;mb-3&quot;&gt;</pre><pre>&lt;label for=&quot;exampleInputPassword1&quot; class=&quot;form-label&quot;&gt;</pre><pre>Password</pre><pre>&lt;/label&gt;</pre><pre>&lt;input</pre><pre>type=&quot;password&quot;</pre><pre>class=&quot;form-control&quot;</pre><pre>id=&quot;exampleInputPassword1&quot;</pre><pre>/&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;</pre><pre>Submit</pre><pre>&lt;/button&gt;</pre><pre>&lt;/form&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/&gt;</pre><pre>);</pre><pre>};</pre><pre>export default Login;</pre><blockquote><strong>Step 9: Now we will edit is Scss go to the _login.scss file</strong></blockquote><pre>.my_login_card{</pre><pre>width: 500px;</pre><pre>position: absolute;</pre><pre>left: 500px;</pre><pre>top: 200px;</pre><pre>.card-body{</pre><pre>background-color: black;</pre><pre>color: white;</pre><pre>}</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*JH0iwZlgS9RDZKmr8WPv_w.png" /></figure><blockquote><strong>Step 10: create a style.scss inside the src folder structure and import our login.sccs file there.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgXbAnoSrqOG0O9ABktOtg.png" /></figure><p>Now click on watch Scss it will create style.css file, now add this style .css file inside index.js file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4KQfQAVMAIUY0Ke7sNKOZA.png" /></figure><blockquote><strong>Step 11: its time to run our application enter npm start in terminal.</strong></blockquote><p>Our application will start running in respective port in my case it is 3001 now just add /login you will see our login page there</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*736oNPrQEzmuZTc0B-M_Fg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*GMnzyk5liX1OOSMN9lDFVg.png" /></figure><blockquote><strong>Step 12 : Now we will move to our functionality part here I will divide this part in 5 subTasks</strong></blockquote><p>1. we need a state to store entered email and password.</p><p>2. we will create payload for our auth api</p><p>3. we have to created onSubmit function to call POST method inside that function.</p><p>4. last if our Login is successful we have to direct our page to Dashboard.</p><p>5. we need a logout button functionality in Dashboard.</p><p>Lets work on Our SubTasks</p><blockquote><strong>SubTask 1: we need a state to store entered email and password.</strong></blockquote><p>Here we will import useState hook from react. We are creating state for Email and Password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*0VJtrWuN0Tw6XDER10jqWQ.png" /></figure><p>We will store the entered value into the state with the help of onChange function. Lets define onChange function for both the input fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*3ktriEuY0WSjzeMqiEXSqg.png" /></figure><pre>onChange={(e) =&gt; setEmail(e.target.value)}</pre><pre>onChange={(e) =&gt; setPassword(e.target.value)}</pre><blockquote><strong>SubTask 2:we will create payload for our auth api</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*JA7TYm7oF7SKVsQspSkXwg.png" /></figure><pre>const payload = {</pre><pre>emailId: email,</pre><pre>password: password,</pre><pre>};</pre><blockquote><strong>SubTask 3: now we have to created onSubmit function.</strong></blockquote><p>we have to call POST method inside that function. For that first install Axios and import it in Login.js page</p><pre>npm i axios</pre><pre>import axios from &quot;axios&quot;;</pre><p>now we will create onClick function on submit button as onSubmitHandler</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*EbFeNnwMxyhHS8aUM4jkPg.png" /></figure><p>lets define our function onSubmitHandler. In this handler we will call our axios Post API and pass our payload to that API as shown bellow, here we will store our token to the localStorage with the help of setItem method. You can see in this case our token is Mytoken.</p><pre>const onSubmitHandler = () =&gt; {</pre><pre>axios</pre><pre>.post(</pre><pre>&quot;PASTE YOUR API HERE&quot;,</pre><pre>payload</pre><pre>)</pre><pre>.then((response) =&gt; {</pre><pre>const response1 = response;</pre><pre>localStorage.setItem(&quot;stringify&quot;, JSON.stringify(response1));</pre><pre>localStorage.setItem(&quot;Mytoken&quot;, response1.data.token);</pre><pre>});</pre><pre>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*Vo_dqy3zawDjVNCgD7NOBA.png" /></figure><p>In inspect mode of browser you can see <br>under the application → storage → localStorage → key as Mytoken</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*J3lhmfx3JDDCcOrLHVGqKw.png" /></figure><blockquote><strong>Subtask 4: if our Login is successful we have to direct our page to Dashboard.</strong></blockquote><p>Our login is successful is determined by token. if token is generated then it is authenticated successfully.</p><p>If token is not there then user must stay in login page only. Lets go to our App.js page import the following</p><pre>import { Redirect } from &quot;react-router-dom&quot;;</pre><p>here I am storing barear Token in a constant with the help of localstorage.getItem and with conditional operator I am redirecting my page conditionally.</p><pre>function App() {</pre><pre>const barearToken = localStorage.getItem(&quot;Mytoken&quot;);</pre><pre>return (</pre><pre>&lt;div className=&quot;wrapper&quot;&gt;</pre><pre>&lt;BrowserRouter&gt;</pre><pre>&lt;Route</pre><pre>render={() =&gt; {</pre><pre>return barearToken ? (</pre><pre>&lt;Redirect to=&quot;/dashboard&quot; /&gt;</pre><pre>) : (</pre><pre>&lt;Redirect to=&quot;/login&quot; /&gt;</pre><pre>);</pre><pre>}}</pre><pre>/&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cVT3kHTtMK8y60nrF4bvpw.png" /></figure><blockquote><strong>Subtask 5 : logout button functionality in Dashboard.</strong></blockquote><p>Now go to the Dashboard.js page and following code</p><pre>import React from &quot;react&quot;;</pre><pre>const Dashboard = () =&gt; {</pre><pre>const logoutHandler = () =&gt; {</pre><pre>localStorage.removeItem(&quot;Mytoken&quot;);</pre><pre>window.location.reload();</pre><pre>};</pre><pre>return (</pre><pre>&lt;&gt;</pre><pre>&lt;div className=&quot;card my_login_card&quot;&gt;</pre><pre>&lt;div className=&quot;card-body&quot;&gt;</pre><pre>&lt;h3&gt;click here to Logout&lt;/h3&gt;</pre><pre>&lt;button</pre><pre>type=&quot;submit&quot;</pre><pre>className=&quot;btn btn-danger&quot;</pre><pre>onClick={logoutHandler}</pre><pre>&gt;</pre><pre>Logout</pre><pre>&lt;/button&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/&gt;</pre><pre>);</pre><pre>};</pre><pre>export default Dashboard;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*hEBbu8hsB27uK1nbF64Z5g.png" /></figure><p>here, we have created a logout button on that button we have defined onClick method, so in logoutHandler we are removing our token from localStorage, here we are using window.location.reload() method to reload our application.</p><blockquote><strong>Step13: Now hit npm start and you can see the login page after adding /login to the rote.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*IKjzq6ZNfAexiU_KTQaYew.png" /></figure><p>Now hit the submit button you will see our path get changed and we are directed towards dashboard page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*UYAbKJeJ9ifyYgGHYDxdDw.png" /><figcaption>Which is look like following image.</figcaption></figure><p>Now click on Logout button you will be redirecting to login page check the local storage you can able to see its token is removed from it.</p><blockquote><strong>Note </strong>please check my dependencies properly if you are facing any version issue.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*Ixy7CTmRXIQ9aAFKsd2SaQ.png" /></figure><p><strong>Wrapping Up</strong></p><p>In this article, we have seen that how to work on Login and Logout functionality. Stay tuned for more updates!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=510fcc1a5ff0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing GraphQL Subscriptions using PubSub and Apollo Server]]></title>
            <link>https://medium.com/@shruti.latthe/implementing-graphql-subscriptions-using-pubsub-and-apollo-server-f9142656008a?source=rss-7fccdee124a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9142656008a</guid>
            <category><![CDATA[subscription]]></category>
            <category><![CDATA[graphql-apollo-server]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[pub-sub]]></category>
            <dc:creator><![CDATA[Shruti Latthe]]></dc:creator>
            <pubDate>Fri, 29 Apr 2022 09:13:44 GMT</pubDate>
            <atom:updated>2022-04-29T11:00:29.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing GraphQL Subscriptions using PubSub and Apollo Server #4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*duVlXtwthtNVPSNI" /></figure><p>Now that we’ve completed the CRUD operations of<a href="https://ultimatecourses.com/blog/graphql-client-side-integration-with-apollo-hooks"> GraphQL</a> , along with that we have learned how to connect graphql to the database, also we have seen how to maintain association between tables. By building out a server and using queries on the graphql playground, it’s time to do some more interesting things and dive into subscriptions and some websockets.</p><p><strong>What is Websockets ?</strong></p><p>websockets are a way to instantly update your user interface. is the connection between server and client, it provides<a href="https://en.wikipedia.org/wiki/Full-duplex"> full-duplex</a> communication.</p><p><strong>What are graphql subscriptions ?</strong></p><p>GraphQL Subscriptions for real-time communication between GraphQL client and server. Subscriptions<strong> </strong>are long-lasting GraphQL read operations that can update their result whenever a particular server-side event occurs. Subscriptions use WebSockets. GraphQL subscriptions are made majorly to listen to when data is <strong>created </strong>on the server, when a data is <strong>updated</strong>, when a data is <strong>deleted</strong>, and when a data is <strong>read </strong>via query.</p><p>The event to emitted is dependent on what the dev wants. The events are pushed from the server to the subscribing clients. Clients subscribe to a server-side event by using the subscription query.</p><p><strong>Required Tools and Packages:</strong></p><ul><li>I am sharing my package.json SS here you can see the required tools and dependencies we will install them in following steps</li><li>primary tools we need Node.js, MySQL-Workbench</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*Q6w-PyRSpg2IMDzb" /></figure><p>if you are new to Data base connection please <strong>click </strong><a href="https://medium.com/@shruti.latthe/graphql-mysql-database-connection-using-sequelize-and-express-in-node-js-885bfc2070ba"><strong>here</strong></a><strong> </strong>you will learn how to connect graphql to database. In this article i will be focusing on how to work with subscription in graphql.</p><blockquote><strong><em>Let’s Start</em></strong></blockquote><p>If you are continuing with previous article then your package.json file might be looking like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*rDpPZGTTpyN2qfBs" /></figure><p>Now we will add some dependencies so lets get started.</p><blockquote><strong>Step 1: if you are new to here and you don’t have project setup then please visit </strong><a href="https://medium.com/@shruti.latthe/build-graphql-folder-structure-and-perform-crud-operations-with-json-data-2-3c2806531b85">here </a><strong>and create your project setup by following this article.</strong></blockquote><blockquote><strong>Step 2: We are implementing GraphQL subscription through two packages, graphql-subscriptions and subscriptions-transport-ws.</strong></blockquote><pre>npm i graphql-subscriptions</pre><pre>npm i subscriptions-transport-ws</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*c6JyzPXYrXNsDsW2" /></figure><blockquote><strong>Step3: Go to typeDefs.js file and let’s add a subscription schema with the root subscription operation type.</strong></blockquote><pre>type <em>Subscription</em> {</pre><pre>studentCreated: <em>Student</em></pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/0*15XTcxvfaJz-jJwP" /></figure><p>We want GraphQL clients to be notified when new-Student are created, so we have added a subscription schema with the root subscription operation type.</p><blockquote><strong>Step4: Now we will resolve our Subscription type for that go to the resolvers.js file</strong></blockquote><p>In order to configure the subscriptions we require PubSub which comes from the terms Publish and Subscribe; its purpose is to publish and subscribe to events. we implemented pubsub from the graphql-subscriptions package for the actual subscription activity.</p><p>The PubSub enables us to publish events to a label and also listen for events associated with a label. In general, PubSub is a basic event emitter that lets us emit and listen to events</p><pre><em>const</em> { PubSub } = require(&#39;graphql-subscriptions&#39;);</pre><pre><em>const</em> pubsub = new PubSub();</pre><pre><em>const</em> STUDENT_CREATED = &#39;STUDENT_CREATED&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/0*NL8sh5abQT-u0MDr" /></figure><p>A PubSub instance enables your server code to both publish events to a particular label and listen for events associated with a particular label.</p><blockquote><strong>Step5: Now update your schema for the newly created Subscription</strong></blockquote><pre>Subscription: {</pre><pre>studentCreated: {</pre><pre>subscribe: () <em>=&gt;</em> pubsub.asyncIterator([STUDENT_CREATED]),</pre><pre>}</pre><pre>}</pre><p>In the Subscription section of our resolver we will subscribe to the event we need via the asyncIterator. For example, studentCreated subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*FFzA4DCfIx4IF4dk" /></figure><blockquote><strong>step 6:Now update our resolver.</strong></blockquote><p>Notice that Subscription resolvers are objects (not functions) with a Subscribe method that returns an AsyncIterable to map with the desired event.</p><p>In our studentCreated mutation we are adding an extra step after the student is created; that step is where we are publishing a STUDENT_CREATED event and sending an object of type std.</p><pre>Mutation:{</pre><pre>async createStudent(<em>root</em>,{ <em>firstName</em>,<em>lastName</em>, <em>age</em>,<em>id</em>},{ <em>Student</em>,<em>Post</em>,<em>Location</em>}){</pre><pre><em>const</em> std= await <em>Student</em>.create({ firstName, lastName, age,id});</pre><pre>await pubsub.publish(STUDENT_CREATED, { studentCreated: std });</pre><pre>return std;</pre><pre>},</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*c46FtSCHf9ldjaoI" /></figure><blockquote><strong>step 7:Now its time to create server for subscriptions</strong></blockquote><p>let’s copy the following code in<strong> server.js </strong>file</p><pre><em>const</em> express    = require(&#39;express&#39;)</pre><pre><em>const</em> { createServer } = require(&#39;http&#39;);</pre><pre><em>const</em> {ApolloServer} =require(&#39;apollo-server-express&#39;);</pre><pre><em>const</em> {  Student } = require(&#39;./sequelize&#39;);</pre><pre><em>const</em> { resolvers } = require(&#39;./gql/resolvers/resolvers&#39;);</pre><pre><em>const</em> { typeDefs } = require(&#39;./gql/typeDefs/typeDefs&#39;);</pre><pre><em>const</em> PORT = process.env.PORT ||  3001;</pre><pre><em>const</em> app = express();</pre><pre><em>const</em> apolloServer = new ApolloServer({ typeDefs, resolvers,context:{ Student}});</pre><pre>apolloServer.applyMiddleware({ app });</pre><pre><em>const</em> httpServer = createServer(app);</pre><pre>apolloServer.installSubscriptionHandlers(httpServer);</pre><pre>httpServer.listen({ port: PORT }, () <em>=&gt;</em>{</pre><pre>console.log(`🚀 Server ready at http://localhost:${PORT}${apolloServer.graphqlPath}`)</pre><pre>})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/0*TfPH3PdtGvInc-4f" /></figure><p>We need to tell the ApolloServer about the subscriptions. To do that we call the method ApolloServer#installSubscriptionHandlers passing in the server.js server instance as an argument.</p><p><strong>step 8:Now its time to run our App</strong></p><p>hit the command yarn start you will see terminal like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*ecNcrxY5HDIPq8w7" /></figure><blockquote><strong>step 9:Now Go to</strong><a href="http://localhost:3001/graphql"><strong> http://localhost:3001/graphql</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PFy1mUUMitPtU1v-" /></figure><p><strong>you will see graphql playground like this</strong></p><blockquote><strong>step 10 :Now it’s time to run our Subscription</strong></blockquote><p>pest the following code in playground and hit play button</p><pre>subscription Subscription {</pre><pre>studentCreated {</pre><pre>std_id</pre><pre>id</pre><pre>firstName</pre><pre>lastName</pre><pre>age</pre><pre>}</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Izb0rbIq6v4jvC7N" /></figure><p>you will see subscription like this it is continuously running</p><blockquote><strong>step 11 :Now click on Newtab on Playground and create student</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NS0bFgxxnZ3IPXIr" /></figure><pre>mutation Mutation($firstName: String, $age: Int, $lastName: String, $createStudentId: Int) {</pre><pre>createStudent(firstName: $firstName, age: $age, lastName: $lastName, id: $createStudentId) {</pre><pre>firstName</pre><pre>id</pre><pre>lastName</pre><pre>age</pre><pre>}</pre><pre>}</pre><pre>{</pre><pre>&quot;firstName&quot;: &quot;shruti&quot;,</pre><pre>&quot;age&quot;: 22,</pre><pre>&quot;lastName&quot;: &quot;Latthe&quot;,</pre><pre>&quot;createStudentId&quot;: 22</pre><pre>}</pre><p>you can see data is created now immediately check our live server for subscription</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rbmDHvsoEh0xJe8d" /></figure><p>you can see our real-time event is listened by the subscription and it is showing real-time data.</p><p><strong>IMP Note</strong></p><p>if you facing any error please comment in this article, before that please try this</p><p>1.delete node modules</p><p>2.delete<strong> </strong>package.json file and its copy</p><p>3.run npm init –yes</p><p>4.install all the necessary packages</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/0*rxM4rL8-pIrRI5YJ" /></figure><p><strong>Wrapping Up</strong></p><p>In this article, we have seen how to build GraphQL subscriptions. We started by first defining type subscription then resolvers and server, later we have checked in playground.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9142656008a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>