<?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 Sehdev Kumar on Medium]]></title>
        <description><![CDATA[Stories by Sehdev Kumar on Medium]]></description>
        <link>https://medium.com/@kumarsehdev600?source=rss-a16534ecee82------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dul4WjkV-Xk-EE1Yt76qHg.jpeg</url>
            <title>Stories by Sehdev Kumar on Medium</title>
            <link>https://medium.com/@kumarsehdev600?source=rss-a16534ecee82------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:17:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kumarsehdev600/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[Fixing Failing React Unit Tests: Let’s Solve Common Issues in Jest.]]></title>
            <link>https://levelup.gitconnected.com/fixing-failing-react-unit-tests-lets-solve-common-issues-in-jest-86fd1d1ff89b?source=rss-a16534ecee82------2</link>
            <guid isPermaLink="false">https://medium.com/p/86fd1d1ff89b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Sehdev Kumar]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 15:59:24 GMT</pubDate>
            <atom:updated>2025-08-28T20:21:04.664Z</atom:updated>
            <content:encoded><![CDATA[<p>Most projects rely on third-party UI libraries to enhance user experience and address common design challenges. These libraries help developers avoid duplicating efforts and reduce redundant code. However, the real challenge begins when it’s time to write unit tests for components built using these libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81N7DtP6SJUMjcWOrrnqWQ.jpeg" /></figure><blockquote><strong>Let’s address some common issues encountered while writing and testing components.</strong></blockquote><h3><strong>1. Tring to access the modals and dialogs elements.</strong></h3><p>Here’s a clear comparison showing how a React component test <strong>fails without mocking </strong><strong>ReactDOM.createPortal</strong> and <strong>passes when it&#39;s mocked properly</strong>. This is especially relevant when testing components like modals or dialogs that use portals.</p><h4>❌ Test Fails Without Mocking createPortal</h4><p>Let’s say you’re testing a Material UI Dialog component:</p><pre>// MyDialog.js<br>import { Dialog, DialogTitle } from &#39;@mui/material&#39;;</pre><pre>export default function MyDialog({ open }) {<br>  return (<br>    &lt;Dialog open={open}&gt;<br>      &lt;DialogTitle&gt;Confirm Action&lt;/DialogTitle&gt;<br>    &lt;/Dialog&gt;<br>  );<br>}</pre><p>And your test:</p><pre>// MyDialog.test.js<br>import { render, screen } from &#39;@testing-library/react&#39;;<br>import MyDialog from &#39;./MyDialog&#39;;</pre><pre>test(&#39;renders dialog title&#39;, () =&gt; {<br>  render(&lt;MyDialog open={true} /&gt;);<br>  expect(screen.getByText(/Confirm Action/i)).toBeInTheDocument();<br>});</pre><p><strong>Result:</strong><br> ❌ The test <strong>fails</strong> because Dialog uses ReactDOM.createPortal, and the dialog content is rendered outside the test container. screen.getByText can’t find it.</p><h4>✅ Test Passes With Mocking createPortal</h4><p>Add this to your test file or setup:</p><pre>jest.mock(&#39;react-dom&#39;, () =&gt; ({<br>  ...jest.requireActual(&#39;react-dom&#39;),<br>  createPortal: (element) =&gt; element,<br>}));</pre><p>Now rerun the same test:</p><pre>test(&#39;renders dialog title&#39;, () =&gt; {<br>  render(&lt;MyDialog open={true} /&gt;);<br>  expect(screen.getByText(/Confirm Action/i)).toBeInTheDocument();<br>});</pre><p><strong>Result:</strong><br> ✅ The test <strong>passes</strong> because the portal is mocked to render inline, making the dialog content accessible to the test environment.</p><h3>2. <strong>Over-Mocking Dependencies</strong></h3><ul><li>Excessive mocking can lead to <strong>unrealistic tests</strong> that don’t reflect actual app behavior.</li><li>Especially common with third-party UI libraries or API calls.</li></ul><p>Let’s walk through a realistic example of <strong>over-mocking dependencies</strong> using your scenario:</p><h4>🧩 Scenario</h4><ul><li>apputils.ts: Contains shared logic or API calls.</li><li>MyButton.tsx: A UI component that uses a function from apputils.ts.</li></ul><h4>📁 apputils.ts</h4><pre>export function getButtonLabel(userType: string): string {<br>  if (userType === &#39;admin&#39;) return &#39;Manage&#39;;<br>  if (userType === &#39;guest&#39;) return &#39;Explore&#39;;<br>  return &#39;Submit&#39;;<br>}</pre><h4>📁 MyButton.tsx</h4><pre>import React from &#39;react&#39;;<br>import { getButtonLabel } from &#39;./apputils&#39;;</pre><pre>export default function MyButton({ userType }: { userType: string }) {<br>  return &lt;button&gt;{getButtonLabel(userType)}&lt;/button&gt;;<br>}</pre><h4>❌ Over-Mocked Test (Unrealistic)</h4><pre>// MyButton.test.tsx<br>jest.mock(&#39;./apputils&#39;, () =&gt; ({<br>  getButtonLabel: () =&gt; &#39;Mocked Label&#39;,<br>}));</pre><pre>import { render, screen } from &#39;@testing-library/react&#39;;<br>import MyButton from &#39;./MyButton&#39;;</pre><pre>test(&#39;renders button label&#39;, () =&gt; {<br>  render(&lt;MyButton userType=&quot;admin&quot; /&gt;);<br>  expect(screen.getByText(&#39;Mocked Label&#39;)).toBeInTheDocument();<br>});</pre><h4>🚨 Problem:</h4><ul><li>The test <strong>always passes</strong>, even if getButtonLabel is broken.</li><li>You’re not testing the real logic or verifying behavior for different userType values.</li><li>If someone changes getButtonLabel to return undefined, this test won’t catch it.</li></ul><h4>✅ Better Test (Minimal or No Mocking)</h4><pre>import { render, screen } from &#39;@testing-library/react&#39;;<br>import MyButton from &#39;./MyButton&#39;;</pre><pre>test(&#39;renders correct label for admin&#39;, () =&gt; {<br>  render(&lt;MyButton userType=&quot;admin&quot; /&gt;);<br>  expect(screen.getByText(&#39;Manage&#39;)).toBeInTheDocument();<br>});</pre><pre>test(&#39;renders correct label for guest&#39;, () =&gt; {<br>  render(&lt;MyButton userType=&quot;guest&quot; /&gt;);<br>  expect(screen.getByText(&#39;Explore&#39;)).toBeInTheDocument();<br>});</pre><h4>✅ Benefits:</h4><ul><li>Tests reflect <strong>real behavior</strong>.</li><li>You catch bugs if getButtonLabel logic changes.</li><li>No need to mock unless the function has side effects (e.g., API calls).</li></ul><h3>3. Problems in API Testing.</h3><p>Absolutely! Here’s a <strong>simple and lightweight example</strong> of testing an API call in a React component without overcomplicating things or hurting performance.</p><h4>🧩 Component: UserGreeting.tsx</h4><pre>import { useEffect, useState } from &#39;react&#39;;</pre><pre>export default function UserGreeting() {<br>  const [name, setName] = useState(&#39;&#39;);</pre><pre>  useEffect(() =&gt; {<br>    fetch(&#39;/api/user&#39;)<br>      .then((res) =&gt; res.json())<br>      .then((data) =&gt; setName(data.name));<br>  }, []);</pre><pre>  return &lt;h1&gt;Hello, {name || &#39;Guest&#39;}!&lt;/h1&gt;;<br>}</pre><h4>✅ Simple Test: UserGreeting.test.tsx</h4><pre>import { render, screen } from &#39;@testing-library/react&#39;;<br>import UserGreeting from &#39;./UserGreeting&#39;;</pre><pre>beforeAll(() =&gt; {<br>  global.fetch = jest.fn(() =&gt;<br>    Promise.resolve({<br>      json: () =&gt; Promise.resolve({ name: &#39;Alice&#39; }),<br>    })<br>  );<br>});</pre><pre>test(&#39;renders user name from API&#39;, async () =&gt; {<br>  render(&lt;UserGreeting /&gt;);<br>  const greeting = await screen.findByText(&#39;Hello, Alice!&#39;);<br>  expect(greeting).toBeInTheDocument();<br>});</pre><h4>🧠 Why This Works Well</h4><ul><li>No real network calls — fetch is mocked.</li><li>Fast and reliable — no delays or external dependencies.</li><li>Focuses on <strong>behavior</strong>, not internal logic.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86fd1d1ff89b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/fixing-failing-react-unit-tests-lets-solve-common-issues-in-jest-86fd1d1ff89b">Fixing Failing React Unit Tests: Let’s Solve Common Issues in Jest.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Component in React Native with Expo SDK 52]]></title>
            <link>https://levelup.gitconnected.com/react-component-in-react-native-with-expo-sdk-52-4e062bd31c10?source=rss-a16534ecee82------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e062bd31c10</guid>
            <category><![CDATA[react-in-react-native]]></category>
            <category><![CDATA[react-native-bridgeless]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[expo]]></category>
            <dc:creator><![CDATA[Sehdev Kumar]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 17:19:38 GMT</pubDate>
            <atom:updated>2024-11-21T22:10:26.513Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsupYIDucbRfis1-6mJeDg.jpeg" /></figure><p>I was extremely excited when the React Native team released the new architecture in SDK 52. With this update, communication between React and the device is now bridgeless. This means no serialized data or asynchronous communication; we can directly write C++ binding code in our React Native application. The introduction of Suspense and the useTransition hook are also fantastic additions. These improvements make React Native more powerful and responsive than ever before.</p><p>However, one of the coolest features I came across was the ability to <strong>render React Web components directly into React Native</strong> using the use dom directive. This feature is extremely useful, and I wish I had known about it earlier, especially considering the pain we went through in my last project at the office. We had to build an entire module from scratch in React Native, even though it was originally designed in React Web. This module used third-party libraries that weren&#39;t available in Expo and React Native APIs, and it required a significant amount of work.</p><p>Let’s take a look at how the use dom directive can be used to integrate React Web components seamlessly into React Native.</p><h3>Example Code:</h3><pre>// ./my-component.tsx<br>&#39;use dom&#39;;<br>export default function DOMComponent({ hello }: { hello: string }) {<br>  return &lt;p&gt;Hello, {hello}&lt;/p&gt;;<br>}</pre><p>In the above code, we define a simple React component DOMComponent, but notice the &#39;use dom&#39; directive at the top. This tells the React Native environment that this component is designed to render in a web environment, allowing it to be used in React Native as well.</p><p>Next, we use this component in a React Native app:</p><pre>import React from &#39;react&#39;;<br>import { Button, View, Alert } from &#39;react-native&#39;;<br>import DOMComponent from &#39;./my-component&#39;;<br><br>export default function App() {<br>  return (<br>    &lt;View style={{ flex: 1 }}&gt;<br>      &lt;DOMComponent hello=&quot;Sehdev&quot; /&gt;<br>      &lt;Button<br>        title=&quot;Focus&quot;<br>        onPress={() =&gt; {<br>          Alert.alert(&quot;Hello World&quot;);<br>        }}<br>      /&gt;<br>    &lt;/View&gt;<br>  );<br>}</pre><p>Here, we import DOMComponent into the main App component and render it inside a View. The DOMComponent receives a hello prop, which is rendered as part of a paragraph (&lt;p&gt; tag) in the component.</p><p>We also have a React Native Button component, which shows an alert when clicked. This demonstrates how you can integrate React Web components in a React Native environment without any complex setup. This new architecture allows for a smoother, more efficient experience when working with both React Native and React Web components.</p><h3>Why is this Cool?</h3><p>In my previous project, we had to replicate a large portion of a web module in React Native. The module depended on a third-party library that wasn’t available in React Native. With this new feature, we could have simply used the React Web component and rendered it directly inside our React Native application. This would have saved a lot of time and effort, especially when dealing with libraries that aren’t yet supported in React Native.</p><p>This bridgeless communication, along with the ability to directly render web components, truly changes the game. It provides a simpler way to integrate and reuse existing web code in your mobile apps, reducing the amount of time spent on development.</p><h3>Conclusion</h3><p>The new features in React Native SDK 52 — such as the bridgeless architecture and support for the use dom directive—open up exciting possibilities for developers. With the ability to easily render React Web components in React Native, the workflow becomes significantly smoother. This is a game-changer for developers who need to build modules that span across both web and mobile platforms, especially when third-party libraries are involved.</p><p>I’m excited to see how this architecture evolves and how we can further enhance our development experience. For now, this new feature is a huge win for React Native developers!</p><p>Happy Coding 🙂.</p><blockquote>“Do practice everyday so that last day would be easy”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e062bd31c10" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/react-component-in-react-native-with-expo-sdk-52-4e062bd31c10">React Component in React Native with Expo SDK 52</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 18 Zoneless]]></title>
            <link>https://levelup.gitconnected.com/angular-18-zoneless-0c8b1e9aa4bc?source=rss-a16534ecee82------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c8b1e9aa4bc</guid>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Sehdev Kumar]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 22:14:31 GMT</pubDate>
            <atom:updated>2024-06-25T22:14:31.314Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular 18 Zoneless: Exploring the Pillars</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7LfIJ7Fr1-GPaSkNuH5wng.jpeg" /></figure><p>“You might not agree, but I wanted Angular to be zoneless and never thought it would happen. Now, it is available in Angular 18 in experimental mode. Do not use it in production.”</p><blockquote>Big Thanks to <strong>Dylan Hunn, </strong><a href="https://medium.com/@mgechev?source=post_page-----e79d5ac0affe--------------------------------">Minko Gechev</a> and<strong> Miles Malerba</strong> from the <strong>Angular team.</strong></blockquote><h3><strong>What is zoneless ?.</strong></h3><p>Yes, that is correct. In a zoneless setup in Angular, the Angular scheduler will not automatically trigger change detection when something changes in the component. Instead, you will need to manually trigger change detection using Angular’s ChangeDetectorRef service.</p><p><strong>Here’s a brief explanation:</strong></p><p>In traditional Angular applications that use Zone.js, Angular automatically triggers change detection when any asynchronous operations (like HTTP requests, setTimeout, user interactions, etc.) are completed. Zone.js monkey-patches these async operations to notify Angular when to run change detection.</p><p>You might think we’ve cooked something, but where are the four pillars? 🧐</p><p>First, we need to set up to check Angular 18’s zoneless APIs.</p><ol><li>Install.</li></ol><pre>ng install @angular/cli@^18<br></pre><p>2. Create New App</p><pre>ng new zoneless-app<br>cd zoneless-app</pre><p>3. Go to app.config.ts file or your application bootstrap file.</p><blockquote>add “<strong><em>provideExperimentalZonelessChangeDetection” API.</em></strong></blockquote><pre>import { ApplicationConfig, provideExperimentalZonelessChangeDetection, provideZoneChangeDetection } from &#39;@angular/core&#39;;<br>import { provideRouter } from &#39;@angular/router&#39;;<br><br>import { routes } from &#39;./app.routes&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [provideExperimentalZonelessChangeDetection(), provideRouter(routes)]<br>};</pre><p>4. Remove<em> zone.js</em> from your polyfills in <em>angular.json</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yg5o-Wwk3BgYwugt4GirVw.png" /></figure><p>Now all setup completed you just need to run application.</p><p>Now, after this setup, Angular will no longer automatically trigger change detection.</p><h3><strong>Why zoneless ? .</strong></h3><p>I would suggest in simpler terms to avoid unnecessary change detection.</p><p>Angular checks from the root to all children whenever any component’s asynchronous operation occurs, which can be inefficient.</p><p>We have the option to overcome this issue using the “changeDetection” strategy “OnPush”, which isolates a component and all its children from the regular change detection cycle.</p><blockquote>What was wrong with OnPush ? .<br>The major drawback of using the “OnPush” change detection strategy is that it requires manual handling of state changes.</blockquote><h3>What are the Four Pillars?.</h3><ol><li>Event Handlers.</li><li>Manage MarkForChanges.</li><li>Async Pipe.</li><li>Signals.</li></ol><h4>Event Handler :</h4><p>Event handlers in Angular are methods in your component class that are bound to events in your template.</p><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: &#39;&lt;button (click)=&quot;onClick()&quot;&gt;{{state}}&lt;/button&gt;&#39;<br>})<br>export class AppComponent {<br> state = &quot;Click Me&quot;;<br>  onClick() {<br>    this.state = &quot;Clicked&quot;;<br>  }<br>}</pre><h4>Manage MarkForChanges:</h4><p>In Angular, markForCheck is used in scenarios where Angular&#39;s default change detection doesn&#39;t pick up changes. This is common in OnPush change detection strategy and now in zoneless.</p><pre>import { ChangeDetectorRef, Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>      {{data}}<br>      &lt;button (click)=&quot;update()&quot;&gt;Update&lt;/button&gt;<br>     `,<br>})<br>export class AppComponent {<br>  data = &#39;Initial Data&#39;;<br><br>  constructor(private cdr: ChangeDetectorRef) { }<br><br>  update() {<br>    this.data = &#39;Updated Data&#39;;<br>    this.cdr.markForCheck();<br>  }<br>}</pre><h4>Async Pipe :</h4><p>The AsyncPipe in Angular automatically subscribes to an Observable or Promise and returns the latest value. It also handles unsubscribing when the component is destroyed.</p><pre>import { CommonModule } from &#39;@angular/common&#39;;<br>import { ChangeDetectionStrategy, ChangeDetectorRef, Component, inject } from &#39;@angular/core&#39;;<br>import { bootstrapApplication } from &#39;@angular/platform-browser&#39;;<br>import { Observable, of } from &#39;rxjs&#39;;<br>import &#39;zone.js&#39;;<br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  template: `<br>     Hello world<br>     {{data$ | async }}<br>  `,<br>  changeDetection: ChangeDetectionStrategy.OnPush,<br>  imports: [CommonModule],<br>})<br>export class App {<br>  name = &#39;Angular&#39;;<br>  data$: Observable&lt;string&gt; | undefined;<br>  cRef = inject(ChangeDetectorRef);<br><br>  constructor() {<br>    setTimeout(() =&gt; {<br>      this.data$ = of(&#39;Hello, AsyncPipe!&#39;);<br>      this.cRef.markForCheck();<br>    }, 4000);<br>  }<br>}<br><br>bootstrapApplication(App);</pre><h4>Signals:</h4><p>I am so happy that Signals are now part of Angular, and their early adoption helps overcome the unnecessary re-rendering overhead of the change detection cycle. Additionally, we can now write in a more declarative programming style, and most of the main APIs are compatible with Signals. This means no more dependency on RxJS for reactivity.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Signal, createSignal } from &#39;@angular/core/signals&#39;;<br><br>@Component({<br>  selector: &#39;app-counter&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;div class=&quot;counter&quot;&gt;<br>      &lt;h1&gt;Counter: {{ count.value }}&lt;/h1&gt;<br>      &lt;button (click)=&quot;decrement()&quot;&gt;-&lt;/button&gt;<br>      &lt;button (click)=&quot;increment()&quot;&gt;+&lt;/button&gt;<br>    &lt;/div&gt;<br>  `,<br>  styles: [`<br>    .counter {<br>      text-align: center;<br>      margin-top: 50px;<br>    }<br>    button {<br>      margin: 0 5px;<br>      padding: 10px;<br>      font-size: 16px;<br>    }<br>  `]<br>})<br>export class CounterComponent {<br>  // Create a signal to manage the count state<br>  count: Signal&lt;number&gt; = createSignal(0);<br><br>  // Method to increment the count<br>  increment() {<br>    this.count.set(this.count.value + 1);<br>  }<br><br>  // Method to decrement the count<br>  decrement() {<br>    this.count.set(this.count.value - 1);<br>  }<br>}</pre><p>No Need for “markForCheck ” or Manual Change Detection</p><p>Due to Signal Pattern we obviously do not need manual change detection checking, the burden of writing manual code is reduced, also the Angular team is converting all APIs into Signals, like Input/Output, ViewChild and many more. .</p><h4>Last Pillar :</h4><p>SSR is the last pillar of angular. For the next post.</p><h4>Conclusion:</h4><p>Angular is now heading in the right direction with the adoption of Signals. Among the pillars supporting Angular, Signals stand out as particularly impactful. They not only facilitate the move towards zoneless operation in Angular 18 but also provide a sense of freedom from unnecessary re-renders and the burden of manual change detection checks. This approach not only improves performance but also promotes a more declarative style of coding.</p><p>Server-Side Rendering (SSR) remains a significant aspect of Angular, which I’ll delve into in a future post. As you continue to explore these four pillars — Event Handlers, Manage MarkForChanges, Async Pipe, and Signals — you’ll discover how they contribute to making your code more readable and simpler.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c8b1e9aa4bc" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/angular-18-zoneless-0c8b1e9aa4bc">Angular 18 Zoneless</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Web Applications with Next.js and Socket.IO]]></title>
            <link>https://medium.com/@kumarsehdev600/real-time-web-applications-with-next-js-and-socket-io-629706516597?source=rss-a16534ecee82------2</link>
            <guid isPermaLink="false">https://medium.com/p/629706516597</guid>
            <dc:creator><![CDATA[Sehdev Kumar]]></dc:creator>
            <pubDate>Sun, 16 Jun 2024 04:29:52 GMT</pubDate>
            <atom:updated>2024-06-16T04:31:20.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YsXnfdR8HtC6z0cuKDxbzw.jpeg" /></figure><p>Real-time web applications have revolutionized user interaction by enabling seamless and instantaneous updates. These applications are crucial for scenarios such as live chat, real-time notifications, collaborative tools, and interactive dashboards, where timely information delivery is essential.</p><p>WebSocket connections form the backbone of such applications, facilitating persistent and bi-directional communication channels between clients (such as web browsers) and servers. Unlike traditional HTTP connections, which are stateless and initiate communication only when a client makes a request, WebSocket connections allow servers to push data to clients as soon as new information becomes available, eliminating the need for clients to continuously poll for updates.</p><p>Implementing WebSocket functionality in a Next.js application using Socket.IO provides a robust solution. Next.js, a popular React framework for building server-rendered applications, integrates seamlessly with Socket.IO to create real-time capabilities. Here’s a detailed guide on how to achieve this:</p><h3>Prerequisites</h3><p>Before we start, ensure you have the following installed:</p><ul><li>Node.js.</li><li>npm (or yarn).</li><li>A basic understanding of Next.js.</li></ul><h3>Step 1: Setting Up the Project</h3><p>First, let’s create a new Next.js project (if you don’t have one already).</p><pre>npx create-next-app real-time-app<br>cd real-time-app</pre><p>Next, install the required dependencies:</p><pre>npm install socket.io socket.io-client</pre><h3>Step 2: Create a Socket.IO Server</h3><p>In Next.js, API routes can be used to set up a server. We’ll create a Socket.IO server within an API route.</p><blockquote>But first, let’s override the NextApiResponse with <strong>NextApiResponseWithSocket</strong>.</blockquote><pre>export interface NextApiResponseWithSocket extends NextApiResponse {<br>  socket: SocketWithIO<br>}<br><br>export interface SocketServer extends HTTPServer {<br>  io?: IOServer | undefined<br>}<br><br>export interface SocketWithIO extends NetSocket {<br>  server: SocketServer<br>}</pre><p>Create a new file in the <strong>pages/api</strong> directory named <strong>socket.ts</strong>.</p><pre><br>import type { NextApiRequest } from &quot;next&quot;<br>import { Server } from &quot;socket.io&quot;<br>import { type NextApiResponseWithSocket } from &quot;~/app/typings/platform&quot;;<br><br><br><br>export default function SocketHandler(_req: NextApiRequest, res: NextApiResponseWithSocket) {<br> if (res.socket.server.io) {<br>    res.end();<br>    return;<br>  }<br>  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument<br>  const io = new Server(res.socket.server);<br><br>  // Event handler for client connections<br>  io.on(&quot;connection&quot;, (socket) =&gt; {<br>    const clientId = socket.id;<br>    console.log(`client connected. ID: ${clientId}`);<br>    // Event handler for receiving messages from the client<br>    socket.on(&quot;message&quot;, (data) =&gt; {<br>      console.log(&quot;Received message From Client:&quot;, data);<br>    });<br><br><br>    // eslint-disable-next-line @typescript-eslint/dot-notation<br><br>    // Event handler for client disconnections<br>    socket.on(&quot;disconnect&quot;, () =&gt; {<br>      console.log(&quot;client disconnected.&quot;);<br>    });<br>  });<br><br>  // Monkey patching to access socket instance globally.<br>  (global as any).io = io<br>  res.socket.server.io = io;<br>  res.end();<br><br><br><br>  res.send({})<br>}</pre><blockquote><strong><em>Monkey patching </em></strong><em>makes the Socket.IO instance globally accessible, ensuring a single instance is used across API calls. This prevents multiple server instances in Next.js, providing efficient, real-time communication for clients connecting to the server.</em></blockquote><pre>// Monkey patching to access socket instance globally.<br>  (global as any).io = io<br>  res.socket.server.io = io;</pre><h3>What We Have Done Till Now.</h3><ul><li><strong>Initialization</strong>: We initialize the Socket.IO server if it doesn’t already exist.</li><li><strong>Connection Event</strong>: When a new client connects, we log the connection.</li><li><strong>Message Event</strong>: When a message is received from a client, it is broadcasted to all other clients.</li><li><strong>Disconnection Event</strong>: When a client disconnects, we log the disconnection.</li></ul><h3><strong>Step 3: Connect to the Socket.IO Server from the Client.</strong></h3><p>We will create a custom React hook that handles the initialization of the connection with the server, which is a convenient approach.</p><p>So, create an custom hook “useWebSocketConnectionHook”.</p><pre>import { useEffect, useRef } from &quot;react&quot;;<br>import { io } from &quot;socket.io-client&quot;;<br>import { WebsocketEventEnum } from &quot;../typings/platform&quot;;<br><br>const useWebSocketConnectionHook = (cb:(arg:unknown)=&gt;void,event:WebsocketEventEnum)=&gt; {<br><br>  // eslint-disable-next-line @typescript-eslint/no-explicit-any<br>  const socketRef = useRef&lt;any&gt;(null);<br><br>  // eslint-disable-next-line react-hooks/exhaustive-deps<br>  function socketClient() {<br>    const socket = io({<br>      transports: [&quot;websocket&quot;],<br>    });<br><br>    socket.on(&quot;connect&quot;, () =&gt; {<br>      socket.on(event as unknown as string, (data) =&gt; {<br>        cb(data);<br>      });<br>      console.log(&quot;Connected&quot;);<br>    });<br><br>    socket.on(&quot;disconnect&quot;, () =&gt; {<br>      console.log(&quot;Disconnected&quot;);<br>    });<br><br>    socket.on(&quot;connect_error&quot;, async (err) =&gt; {<br>      console.log(`connect_error due to ${err.message}`);<br>      await fetch(&#39;/api/socket&#39;);<br>    });<br><br>  <br>    socketRef.current = socket;<br>  }<br><br>  useEffect(() =&gt; {<br>    socketClient();<br>    return ()=&gt; {<br>      socketRef?.current?.disconnect();<br>    }<br>  // eslint-disable-next-line react-hooks/exhaustive-deps<br>  },[]);<br><br><br>}<br><br>export default useWebSocketConnectionHook;</pre><p>“Now, use the hook in a client-side component. Hooks are supported only in client-side components, not server-side components.”</p><pre><br>import { useEffect, useState } from &#39;react&#39;;<br>import useWebSocketConnectionHook from &quot;./useWebsocketHook&quot;;<br><br>export default function Home() {<br>  <br>    useWebSocketConnectionHook(() =&gt; {<br>     console.log(&quot;me conected&quot;);<br>   }, &quot;MY_EVENT_NAME&quot;);<br><br>  return (<br>     <br>  );<br>}</pre><p>It takes two arguments:</p><p><strong>The first argument</strong> is a callback function <em>() =&gt; { console.log(&quot;me connected&quot;); }</em>.</p><p>This function will be called whenever the WebSocket server sends an event named &quot;MY_EVENT_NAME&quot;.</p><p><strong>The second argument </strong>&quot;MY_EVENT_NAME&quot; specifies the type of event that the hook should listen for on the WebSocket connection.</p><h3>Conclusion</h3><p>By following these steps, you can create a real-time web application using Next.js and Socket.IO. This setup allows for instantaneous communication between the client and server, enabling features like live chat and notifications.</p><p>Happy coding! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=629706516597" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 17+ Dependency Injection Simplified: Exploring useClass, useExisting, useValue, and…]]></title>
            <link>https://medium.com/@kumarsehdev600/angular-dependency-injection-simplified-exploring-useclass-useexisting-usevalue-and-usefactory-ab3d16c5d0df?source=rss-a16534ecee82------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab3d16c5d0df</guid>
            <dc:creator><![CDATA[Sehdev Kumar]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 17:33:56 GMT</pubDate>
            <atom:updated>2024-03-18T06:16:30.981Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular 17+ Dependency Injection Simplified: Exploring useClass, useExisting, useValue, and useFactory.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kQSN9UH8ctplHyh2" /></figure><p><strong>Angular’s</strong> dependency<strong> injection (DI)</strong> system is a powerful feature that allows developers to manage dependencies and promote modularity within applications. In this blog post, we’ll delve into four essential techniques for dependency injection in Angular: <strong>useClass</strong>, <strong>useExisting</strong>, <strong>useValue</strong>, and <strong>useFactory</strong>. By understanding and mastering these techniques, you can revolutionize how dependencies are managed in your Angular projects.</p><h3><strong>useClass</strong></h3><p><strong>Angular’s useClass</strong> configuration in dependency <strong>injection</strong> is like a substitute teacher. When a <strong>component</strong> asks for a service, <strong>useClass</strong> steps in and provides a different service <strong>instead</strong> of the original one. It’s like having a stand-in ready to take over, creating an instance of the <strong>replacement</strong> service <strong>whenever</strong> it’s needed.</p><pre>@Component({<br>  selector: &#39;app-injections-tester&#39;,<br>  standalone: true,<br>  imports: [],<br>  templateUrl: &#39;./injections-tester.component.html&#39;,<br>  styleUrl: &#39;./injections-tester.component.scss&#39;,<br>  // useClass <br>  providers:[{<br>    provide: MainService,<br>    useClass: ExperimentsService,<br>  }]<br>})<br>export class InjectionsTesterComponent {<br><br><br>    // Service Injection<br>    ms = inject(MainService);<br>    es = inject(ExperimentsService);<br><br>    constructor() {<br>      // is ms and es has same instance <br>      console.log(this.ms === this.es) // False<br><br>      // What will be the output of MainService ?<br>      // it point to ExperimentsService<br>      console.log(this.ms); <br><br><br>    }<br>}</pre><p>Let’s create two services: <strong>MainService</strong> and <strong>ExperimentsService</strong>. In the component metadata, we&#39;ll use the <strong>providers</strong> array as shown in the above code.</p><p>When you run the code, in the <strong>constructor</strong>, we’ll<strong> console.log</strong> the comparison of the services and the value of <strong>MainService</strong>.</p><p>Just take a look at what happens.</p><blockquote>“Both instances are not the same, and the value of `MainService` changes to `ExperimentsService` — it’s a replacement of the instance. This feature is useful when you don’t want to change existing code but need to switch the service instead.”</blockquote><h3><strong>useExisting</strong></h3><p><strong>useExisting</strong> is mostly similar to <strong>useClass</strong>, just slightly different in terms of how <strong>instances</strong> are created when <strong>injected</strong> into the component.</p><pre>@Component({<br>  ...<br>  // useClass <br>  providers:[{<br>    provide: MainService,<br>    useExisting: ExperimentsService,<br>  }]<br>...<br>})<br>export class InjectionsTesterComponent {<br><br>    // Service Injection<br>    ms = inject(MainService);<br>    es = inject(ExperimentsService);<br><br>    constructor() {<br>      // is ms and es has same instance <br>      console.log(this.ms === this.es) // true<br><br>      // What will be the output of MainService ?<br>      // it point to ExperimentsService<br>      console.log(this.ms); <br><br>    }<br>}</pre><blockquote>“This time, both instances are the same, and <strong>MainService</strong> points to <strong>ExperimentsService</strong>.”</blockquote><h3><strong>useValue</strong></h3><p>UseValue is utilized to supply <strong>primitive</strong> values or any object directly as dependencies. This is particularly useful since <strong>Angular’s</strong> Dependency Injection<strong> does not permit</strong> the usage of<strong> plain objects</strong> without the Injectable decorator.</p><p>For example now you can assign the <strong>strings</strong>, <strong>numbers</strong> or any <strong>object</strong>.</p><pre>@Component({<br>  ...<br>  // useClass <br>  providers:[{<br>    provide: MainService,<br>    useValue: {name:&#39;SK&#39;,address:&quot;HYD&quot;},<br>  }]<br>...a<br>})<br>export class InjectionsTesterComponent {<br><br>    // Service Injection<br>    ms = inject(MainService);<br><br>    constructor() {<br>      // What will be the output<br>      console.log(this.ms); // {name:&#39;SK&#39;,address:&quot;HYD&quot;}<br><br>    }<br>}</pre><blockquote>“Unlike <strong>useClass</strong> and <strong>useExisting</strong>, <strong>useValue</strong> doesn’t involve creating <strong>instances</strong> of services. Instead, it directly provides any value to the service instance, regardless of its type.”</blockquote><h3>useFactory</h3><p><strong>UseFactory</strong> is used when you need to <strong>dynamically</strong> create and provide a dependency based on certain <strong>conditions</strong> or <strong>parameters</strong>. It’s like having a factory that produces instances of the required service<strong> on-demand</strong>, allowing for flexible customization.</p><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  ...<br>  providers: [<br>    {<br>      provide: MainService,<br>      useFactory: () =&gt; {<br>        if (isLoggedIn) {<br>          return { name: &#39;SK&#39;, address: &#39;HYD&#39; };<br>        } else {<br>          return { name: &#39;Other&#39;, address: &#39;Other Address&#39; };<br>        }<br>      }<br>    }<br>  ]<br>})<br>export class InjectionsTesterComponent {<br><br>    // Service Injection<br>    ms: any; // Declare ms as any type since we don&#39;t know the exact type until runtime<br><br>    constructor(private mainService: MainService) {<br>      // Assign the value of MainService<br>      this.ms = mainService;<br><br>      // Output<br>      console.log(this.ms); // Depending on the condition, it will log either { name: &#39;SK&#39;, address: &#39;HYD&#39; } or { name: &#39;Other&#39;, address: &#39;Other Address&#39; }<br>    }<br>}</pre><blockquote>Based on the <strong>isLoggedIn</strong> flag, it either creates instances or returns the value dynamically, allowing for changes in values based on runtime conditions.</blockquote><h3><strong>Conclusion</strong></h3><p>In conclusion, Angular’s dependency injection system provides developers with a variety of tools to efficiently manage dependencies within their applications. By leveraging techniques such as <strong>useClass</strong>, <strong>useExisting</strong>, <strong>useValue</strong>, and <strong>useFactory</strong>, developers can enhance modularity, maintainability, and flexibility in their Angular projects. These strategies enable seamless <strong>substitution</strong> of implementations, reuse of existing services, direct provision of values, and dynamic dependency creation based on runtime conditions. Overall, mastering Angular’s dependency injection system is essential for building <strong>robust</strong> and <strong>scalable</strong> applications.</p><p><em>“Welcome to Angular Craft! Embrace DI as your coding sidekick. Keep useClass-ing, useExisting-ing, useValue-ing, and useFactory-ing for smooth Angular apps! 🚀”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab3d16c5d0df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Mastering Strategy Patterns with Compose and Pipe in JavaScript: A Fun Journey into Functional…]]></title>
            <link>https://medium.com/@kumarsehdev600/mastering-strategy-patterns-with-compose-and-pipe-in-javascript-a-fun-journey-into-functional-67763d0043d8?source=rss-a16534ecee82------2</link>
            <guid isPermaLink="false">https://medium.com/p/67763d0043d8</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[desgin-patterns]]></category>
            <dc:creator><![CDATA[Sehdev Kumar]]></dc:creator>
            <pubDate>Sat, 27 Jan 2024 15:21:05 GMT</pubDate>
            <atom:updated>2024-01-27T15:22:53.151Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>“Mastering Strategy Patterns with Compose and Pipe in JavaScript: A Fun Journey into Functional Programming”</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EVa895kkSe3G7TWJGqOcw.png" /></figure><p>In the vast landscape of JavaScript, where paradigms collide and libraries flourish, mastering functional programming techniques becomes a superpower for developers. Today, we embark on an exciting journey exploring the synergy of strategy patterns, compose, and pipe functions. We’ll unleash the power of functional programming to create flexible and elegant solutions.</p><blockquote><strong>The Beauty of Functional Programming</strong></blockquote><p>Functional programming (FP) is more than just a programming paradigm; it’s a mindset that empowers developers to write concise, readable, and expressive code. Two fundamental concepts in FP are <strong>compose</strong> and <strong>pipe</strong>.</p><p><strong>Compose</strong>: It allows you to create a new function by combining multiple functions, where the result of one function becomes the input for the next.</p><p><strong>Pipe</strong>: Similar to compose, but the functions are applied from left to right, creating a more readable flow.</p><blockquote><strong>The Strategy Pattern</strong></blockquote><p>Enter the strategy pattern, a design pattern that encapsulates a family of algorithms and allows them to be interchangeable. Combining the strategy pattern with compose and pipe functions in JavaScript can lead to code that is not only powerful but also a joy to work with.</p><p><strong>A Fun Example: Building a Dynamic Text Transformer</strong></p><p>Imagine you’re building a text transformation library where users can apply various transformations to a given string. Each transformation is a strategy, and users can compose or pipe these strategies to create powerful and flexible transformations.</p><p>Let’s start with defining our strategy interface:</p><pre>// Strategy interface<br>class TextFormatter {<br>  format(text) {<br>    throw new Error(&quot;This method must be overridden by concrete strategies&quot;);<br>  }<br>}<br><br>// Concrete strategy classes<br>class UpperCaseFormatter extends TextFormatter {<br>  format(text) {<br>    return text.toUpperCase();<br>  }<br>}<br><br>class LowerCaseFormatter extends TextFormatter {<br>  format(text) {<br>    return text.toLowerCase();<br>  }<br>}<br><br>class CapitalizeFormatter extends TextFormatter {<br>  format(text) {<br>    return text.replace(/\b\w/g, (match) =&gt; match.toUpperCase());<br>  }<br>}<br><br>// Context class that uses the strategy<br>class TextEditor {<br>  constructor(formatter) {<br>    this.formatter = formatter;<br>  }<br><br>  setFormatter(formatter) {<br>    this.formatter = formatter;<br>  }<br><br>  formatText(text) {<br>    return this.formatter.format(text);<br>  }<br>}<br><br>// Client code<br>const upperCaseFormatter = new UpperCaseFormatter();<br>const lowerCaseFormatter = new LowerCaseFormatter();<br>const capitalizeFormatter = new CapitalizeFormatter();<br><br>const textEditor = new TextEditor(upperCaseFormatter);<br><br>console.log(&quot;Original text: Hello, World!&quot;);<br><br>// Use upper case formatting strategy<br>textEditor.setFormatter(upperCaseFormatter);<br>console.log(&quot;Formatted text (Upper Case):&quot;, textEditor.formatText(&quot;Hello, World!&quot;));<br><br>// Use lower case formatting strategy<br>textEditor.setFormatter(lowerCaseFormatter);<br>console.log(&quot;Formatted text (Lower Case):&quot;, textEditor.formatText(&quot;Hello, World!&quot;));<br><br>// Use capitalize formatting strategy<br>textEditor.setFormatter(capitalizeFormatter);<br>console.log(&quot;Formatted text (Capitalize):&quot;, textEditor.formatText(&quot;Hello, World!&quot;));</pre><p>These strategies are simple, yet they showcase the power of encapsulating different behaviors.<strong> Now, let’s implement the compose and pipe functions:</strong></p><pre>// Strategy interface<br>class TextFormatter {<br>  format(text) {<br>    throw new Error(&quot;This method must be overridden by concrete strategies&quot;);<br>  }<br>}<br><br>// Concrete strategy classes<br>class UpperCaseFormatter extends TextFormatter {<br>  format(text) {<br>    return text.toUpperCase();<br>  }<br>}<br><br>class LowerCaseFormatter extends TextFormatter {<br>  format(text) {<br>    return text.toLowerCase();<br>  }<br>}<br><br>class CapitalizeFormatter extends TextFormatter {<br>  format(text) {<br>    return text.replace(/\b\w/g, (match) =&gt; match.toUpperCase());<br>  }<br>}<br><br>// Context class that uses the strategy<br>class TextEditor {<br>  constructor(formatter) {<br>    this.formatter = formatter;<br>  }<br><br>  setFormatter(formatter) {<br>    this.formatter = formatter;<br>  }<br><br>  formatText(text) {<br>    return this.formatter.format(text);<br>  }<br>}<br><br>// Client code<br>const upperCaseFormatter = new UpperCaseFormatter();<br>const lowerCaseFormatter = new LowerCaseFormatter();<br>const capitalizeFormatter = new CapitalizeFormatter();<br><br>const textEditor = new TextEditor(upperCaseFormatter);<br><br><br>// Compose function<br>const compose = (...functions) =&gt; input =&gt; functions.reduceRight((acc, fn) =&gt; fn(acc), input);<br><br>// Pipe function<br>const pipe = (...functions) =&gt; input =&gt; functions.reduce((acc, fn) =&gt; fn(acc), input);<br><br><br><br>// Create a pipe for formatting in a specific order<br>const formatPipeline = pipe(<br>  new UpperCaseFormatter().format,<br>  new CapitalizeFormatter().format,<br>  new LowerCaseFormatter().format<br>);<br><br>// Use the pipe to format text<br>console.log(&quot;Formatted text (Pipeline):&quot;, formatPipeline(&quot;Hello, World!&quot;));<br><br>// Create a compose for formatting in a reverse order<br>const formatCompose = compose(<br>  new LowerCaseFormatter().format,<br>  new CapitalizeFormatter().format,<br>  new UpperCaseFormatter().format<br>);<br><br>// Use the compose to format text<br>console.log(&quot;Formatted text (Compose):&quot;, formatCompose(&quot;Hello, World!&quot;));<br><br><br><br><br><br></pre><p>In this example, we’ve defined three text transformation strategies (LowerCaseFormatter, CapitalizeFormatter, and UpperCaseFormatter) and showcased how to compose and pipe them to create complex transformations.</p><h3>Conclusion</h3><p>As we conclude our adventure into the world of functional programming, strategy patterns, compose, and pipe functions, we’ve only scratched the surface of what’s possible. Embracing these concepts can lead to cleaner, modular, and more maintainable code. So go ahead, experiment, and let the functional magic unfold in your JavaScript projects!</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67763d0043d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Angular Project Management with a Custom Makefile]]></title>
            <link>https://medium.com/@kumarsehdev600/simplifying-angular-project-management-with-a-custom-makefile-030d43b42ee5?source=rss-a16534ecee82------2</link>
            <guid isPermaLink="false">https://medium.com/p/030d43b42ee5</guid>
            <dc:creator><![CDATA[Sehdev Kumar]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 01:19:43 GMT</pubDate>
            <atom:updated>2023-12-12T01:28:32.568Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jhzn3FTiKd2AzbjM9_0C-A.jpeg" /></figure><p>Managing an <strong>Angular</strong> project efficiently requires a set of consistent commands to handle various tasks, from generating components to running tests and deploying the <strong>application</strong>. A Makefile can streamline this process by encapsulating these commands into <strong>easy-to-use</strong> targets. In this blog post, we’ll explore a Makefile designed for Angular projects that simplifies common tasks and enhances project <strong>maintainability</strong>.</p><h3>Understanding the Makefile Structure</h3><p>Let’s break down the key components of the Makefile:</p><h3>Angular Version and Environment</h3><p>The Makefile starts by defining essential variables such as the Node.js version, Angular version, Angular CLI alias, and project directories.</p><pre>NODE_VERSION=18<br>ANGULAR_VERSION=17<br>NG_CLI = npx -p @angular/cli@$(ANGULAR_VERSION)<br>SOURCE_DIR = src<br>DIST_DIR = dist</pre><p>These variables are crucial for maintaining a consistent development environment across different machines.</p><h3>Functions for Angular Version and IP Address</h3><p>Two functions are defined to fetch the Angular version and the local machine’s IP address. These functions enhance the Makefile’s flexibility and can be reused in various targets.</p><pre>define get_angular_version<br>    $$(. $(HOME)/.nvm/nvm.sh &amp;&amp; nvm use $(NODE_VERSION) &amp;&amp; $(NG_CLI) ng version)<br>endef<br><br>define get_ip<br>    $(shell hostname -I | cut -d&#39; &#39; -f1)<br>endef</pre><p>The Makefile includes several targets to execute common Angular CLI commands. Here are some notable ones:</p><ul><li><strong>g-state, g-actions, g-effects, g-feature</strong>: Generate NgRx store state, actions, effects, and feature.</li><li><strong>gs, gc</strong>: Generate Angular service and component.</li><li><strong>run</strong>: Start the development server with a specified IP address and port.</li><li><strong>build</strong>: Build the Angular application.</li><li><strong>rmn</strong>: Remove the dist directory.</li><li><strong>i</strong>: Install project dependencies using npm.</li><li><strong>v:</strong> Display the Angular version.</li><li>test: Run Angular tests.</li><li><strong>lint: </strong>Perform linting using a custom script.</li></ul><h3>Docker Commands</h3><p>The Makefile also includes targets for Docker commands, allowing for seamless integration with containerized environments:</p><pre>dc-up:<br>    sudo docker-compose up --remove-orphans<br><br>dc-down:<br>    sudo docker-compose down<br><br>dc-remove-all:<br>    sudo docker system prune -a</pre><h3><strong>Complete file:-</strong></h3><pre># Makefile for Angular Project<br>#! Function to read Angular version<br>define get_angular_version<br> $$(. $(HOME)/.nvm/nvm.sh &amp;&amp; nvm use $(NODE_VERSION) &amp;&amp; $(NG_CLI) ng version)<br>endef<br><br>#! Function to read the your local ip address<br>define get_ip<br> $(shell hostname -I | cut -d&#39; &#39; -f1)<br>endef<br><br><br>#! Variables<br>NODE_VERSION=18<br>ANGULAR_VERSION=17<br>NG_CLI = npx -p @angular/cli@$(ANGULAR_VERSION)<br>SOURCE_DIR = src<br>DIST_DIR = dist<br><br><br># Targets<br>.PHONY:g-state g-actions g-effects g-feature gs gc run build rmn i -v test lint dc-up dc-down<br><br>#! System Commands<br>ip:<br> @echo $(call get_ip)<br><br>#* Angular Ngrx Cli Commands<br># !Make sure you have installed the ngrx schemetics and add to the angular.json file in &quot;cli&quot; option, otherwise the commonds will not work.<br>g-state:<br> @. $(HOME)/.nvm/nvm.sh &amp;&amp; nvm use $(NODE_VERSION) &amp;&amp; $(NG_CLI) ng generate store --root --state-path --module<br>g-actions:<br> @. $(HOME)/.nvm/nvm.sh &amp;&amp; nvm use $(NODE_VERSION) &amp;&amp; $(NG_CLI) ng generate action --group<br>g-effects:<br> @. $(HOME)/.nvm/nvm.sh &amp;&amp; nvm use $(NODE_VERSION) &amp;&amp; $(NG_CLI) ng generate effect --group<br>g-feature:<br> @. $(HOME)/.nvm/nvm.sh &amp;&amp; nvm use $(NODE_VERSION) &amp;&amp; $(NG_CLI) ng generate feature<br><br>#! Angular cli commands<br>gs:<br> @. $(HOME)/.nvm/nvm.sh &amp;&amp; nvm use $(NODE_VERSION) &amp;&amp; $(NG_CLI) ng g s<br><br>gc:<br> @. $(HOME)/.nvm/nvm.sh &amp;&amp; nvm use $(NODE_VERSION) &amp;&amp; $(NG_CLI) ng g c<br><br>run:<br> @. $(HOME)/.nvm/nvm.sh &amp;&amp; nvm use $(NODE_VERSION) &amp;&amp; $(NG_CLI) ng serve --host $(call get_ip) --port 4200<br><br>build:<br> @. $(HOME)/.nvm/nvm.sh &amp;&amp; nvm use $(NODE_VERSION) &amp;&amp; $(NG_CLI) ng build<br><br>rmn:<br> rm -rf $(DIST_DIR)<br><br>i:<br> @. $(HOME)/.nvm/nvm.sh &amp;&amp; nvm use $(NODE_VERSION) &amp;&amp; $(NG_CLI) npm install --force<br><br>v:<br> @echo &quot;Angular Version:$(call get_angular_version)&quot;<br><br>test:<br> @. $(HOME)/.nvm/nvm.sh &amp;&amp; nvm use $(NODE_VERSION) &amp;&amp; $(NG_CLI) ng test<br><br>lint:<br> $(shell ./linting.sh)<br><br>#! Docker Cli Commands<br>dc-up:<br> sudo docker-compose up --remove-orphans<br><br>dc-down:<br> sudo docker-compose down<br><br>dc-remove-all:<br> sudo docker system prune -a<br><br><br><br>#! Default target<br>.DEFAULT_GOAL := serve</pre><h3>Simplifying Angular Development</h3><p>By using this Makefile, developers can significantly simplify their workflow. Running common tasks, such as generating components, building the application, or starting the development server, becomes as simple as executing a make command. Additionally, the Makefile promotes consistency across development environments, ensuring that everyone works with the same versions of Node.js and Angular CLI.</p><p>To enhance this Makefile further, consider customizing it based on your project’s specific needs. Add more targets, incorporate additional checks, or integrate other tools to tailor the Makefile to your workflow. With this approach, you can create a robust and standardized development environment for your Angular projects.</p><p>In conclusion, a well-structured Makefile can be a valuable asset for Angular developers, providing a unified and efficient way to manage their projects. Whether you are working on a small personal project or a large enterprise application, a Makefile can contribute to a smoother development experience and improved project maintainability.</p><h3>Conclusion</h3><p>This Makefile serves as a powerful tool for Angular developers, streamlining common development tasks and ensuring consistency across different environments. It encapsulates Angular CLI commands, Docker operations, and custom scripts, providing a unified and efficient workflow. Developers can further customize and extend this Makefile to suit the specific needs of their projects.</p><p>Happy Makefile 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=030d43b42ee5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling the Power of NgRx Out of the Box: Conquering Boilerplate with createFeature and…]]></title>
            <link>https://medium.com/@kumarsehdev600/unveiling-the-power-of-ngrx-out-of-the-box-conquering-boilerplate-with-createfeature-and-2ea574a63e58?source=rss-a16534ecee82------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ea574a63e58</guid>
            <category><![CDATA[reduce-the-code]]></category>
            <category><![CDATA[actionsgroups-ngrx]]></category>
            <category><![CDATA[createfeature]]></category>
            <category><![CDATA[ngrx]]></category>
            <dc:creator><![CDATA[Sehdev Kumar]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 04:22:08 GMT</pubDate>
            <atom:updated>2023-12-01T10:48:12.535Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Unveiling the Power of NgRx Out of the Box: Conquering Boilerplate with </strong><strong>createFeature and </strong><strong>ActionsGroup.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*zPkOvGWIUZZkzxr7" /></figure><p>Initially, let’s delve into how this post <strong>reshapes</strong> your <strong>outlook</strong>, particularly when faced with <strong>apprehension</strong> about <strong>integrating</strong> <strong>NgRx</strong> into your <strong>Angular</strong> applications.</p><p><strong>Here are the problems and solutions that I know and will share with you.</strong></p><h3><strong>Problems:</strong></h3><p>“When exploring additional aspects of a framework or library, many people struggle with self-doubt and insecurity. This sentiment is entirely natural and need not be a cause for concern. So, what exactly is the hurdle in adopting <strong>NgRx</strong>? The <strong>prominent</strong> issue frequently mentioned is the surplus of <strong>boilerplate</strong> code.”</p><p>What is the<strong> surplus of boilerplate</strong>?</p><p>The Ngrx Store concept enables data sharing and acts as a global state for components. So, there are four key components of the <strong>Ngrx Actions, Reducers, Effects, </strong>and<strong> Selectors.</strong></p><p>Taking an example would help us understand this better. Let&#39;s consider building an &quot;Upload file Application&quot; in A<strong>ngular</strong>. We need to break this down into <strong>chunks</strong> and create actions for <strong>Ngrx</strong>.</p><p>Instead of creating the <strong>Actions</strong> individually, we grouped them just see below.</p><h3><strong>Actions Before:</strong></h3><pre>export const uploadRequest = createAction(&#39;[File Upload] Upload Request&#39;, props&lt;{ file: string }&gt;());<br>export const uploadProgress = createAction(&#39;[File Upload] Upload Progress&#39;, props&lt;{ progress: number }&gt;());<br>export const uploadSuccess = createAction(&#39;[File Upload] Upload Success&#39;, props&lt;{ result: any }&gt;());<br>export const uploadFailure = createAction(&#39;[File Upload] Upload Failure&#39;, props&lt;{ error: any }&gt;());<br><br>export const fetchFilesRequest = createAction(&#39;[Files Fetched] Request to Fetch the Files&#39;, emptyProps());<br>export const fetchFilesSuccess = createAction(&#39;[Files Fetched] Success to Fetch the Files&#39;, props&lt;{ response: any }&gt;());<br>export const fetchFilesFailure = createAction(&#39;[Files Fetched] Failure to Fetch the Files&#39;, props&lt;{ error: any }&gt;());</pre><h3><strong>Actions After :</strong></h3><pre>import { createAction, createActionGroup, emptyProps, props } from &#39;@ngrx/store&#39;<br><br>export const FileUploadActions = createActionGroup({<br>  source: &#39;Upload File&#39;,<br>  events: {<br>    &#39;[File Upload] Upload Request&#39;: props&lt;{ file: string }&gt;(),<br>    &#39;[File Upload] Upload Progress&#39;: props&lt;{ progress: number }&gt;(),<br>    &#39;[File Upload] Upload Success&#39;: props&lt;{ result: any }&gt;(),<br>    &#39;[File Upload] Upload Failure&#39;: props&lt;{ error: any }&gt;(),<br><br>    &#39;[Files Fetched] Request to Fetch the Files&#39;: emptyProps(),<br>    &#39;[Files Fetched] Success to Fetch the Files&#39;: props&lt;{ response: any }&gt;(),<br>    &#39;[Files Fetched] Failure to Fetch the Files&#39;: props&lt;{ error: any }&gt;(),<br>  },<br>})</pre><p>Although it may look the same, the code is actually more convenient. Just wait for a rapid glance.</p><blockquote>Problems weren’t defining the distinct <strong>Actions,</strong> keeping the <strong>Actions</strong> unique is a good thing. So, Now we will talk about the <strong>Reducers.</strong></blockquote><pre>const FileUploadReducer =  createReducer(<br>    initialState, // Initial state for the feature<br>    // Define reducer logic for different actions using the &#39;on&#39; function<br>    on(FileUploadActions[&#39;[FileUpload]UploadRequest&#39;], (state,{file}) =&gt; {<br>      // Reset the state when an upload request is made<br>      return {<br>        ...state,<br>        file<br><br>      };<br>    }),<br>    on(<br>      FileUploadActions[&#39;[FileUpload]UploadProgress&#39;],<br>      (state, { progress }) =&gt; {<br>        // Update the state with the progress when upload progress action is dispatched<br>        return {<br>          ...state,<br>          progress,<br>        };<br>      },<br>    ),<br>    on(FileUploadActions[&#39;[FileUpload]UploadSuccess&#39;], (state, { result }) =&gt; {<br>      // Update the state with the result when upload success action is dispatched<br>      return {<br>        ...state,<br>        result,<br>      };<br>    }),<br>    on(FileUploadActions[&#39;[FileUpload]UploadFailure&#39;], (state, { error }) =&gt; {<br>      // Update the state with the error when upload failure action is dispatched<br>      return {<br>        ...state,<br>        error,<br>      };<br>    }),<br><br>    on(FileUploadActions[&#39;[FilesFetched]RequestToFetchTheFiles&#39;], (state) =&gt; {<br>      // Update the state with the error when upload failure action is dispatched<br>      return {<br>        ...state,<br>      };<br>    }),<br>     on(FileUploadActions[&#39;[FilesFetched]SuccessToFetchTheFiles&#39;], (state,{response}) =&gt; {<br>      // Update the state with the error when upload failure action is dispatched<br>      return {<br>        ...state,<br>        response:response[&#39;body&#39;]<br>      };<br>    }),<br>     on(FileUploadActions[&#39;[FilesFetched]FailureToFetchTheFiles&#39;], (state,{error}) =&gt; {<br>      // Update the state with the error when upload failure action is dispatched<br>      return {<br>        ...state,<br>        error<br>      };<br>    }),</pre><p>After seeing the Above code what do you think is the actual problem with <strong>increasing</strong> the code <strong>boilerplates</strong>, yes it does. but we do not have options to reduce more because for every <strong>Action</strong> we have to do some manipulations for the state and return it.</p><blockquote>Again even if it is correct we are missing the <strong>grail</strong>, wait we finally find this. let’s move to<strong> Selectors.</strong></blockquote><blockquote>As you know <strong>Selectors</strong> are used to get the state data through the <strong>Store</strong> into <strong>components.</strong></blockquote><pre>import { createFeatureSelector, createSelector } from &#39;@ngrx/store&#39;;<br><br>// Define the feature state interface<br>export interface FileUploadState {<br>  file: any; // Replace &#39;any&#39; with the actual type of your file<br>  progress: number;<br>  result: any; // Replace &#39;any&#39; with the actual type of your result<br>  error: any; // Replace &#39;any&#39; with the actual type of your error<br>  response: any; // Replace &#39;any&#39; with the actual type of your response<br>}<br><br>// Create a feature selector for the FileUpload feature<br>export const selectFileUploadFeature = createFeatureSelector&lt;FileUploadState&gt;(&#39;fileUpload&#39;);<br><br>// Create individual selectors for each piece of state<br>export const selectFile = createSelector(selectFileUploadFeature, (state: FileUploadState) =&gt; state.file);<br>export const selectProgress = createSelector(selectFileUploadFeature, (state: FileUploadState) =&gt; state.progress);<br>export const selectResult = createSelector(selectFileUploadFeature, (state: FileUploadState) =&gt; state.result);<br>export const selectError = createSelector(selectFileUploadFeature, (state: FileUploadState) =&gt; state.error);<br>export const selectResponse = createSelector(selectFileUploadFeature, (state: FileUploadState) =&gt; state.response);<br><br>// Optionally, you can create a combined selector to select the entire state<br>export const selectFileUploadState = createSelector(<br>  selectFile,<br>  selectProgress,<br>  selectResult,<br>  selectError,<br>  selectResponse,<br>  (file, progress, result, error, response) =&gt; ({<br>    file,<br>    progress,<br>    result,<br>    error,<br>    response,<br>  })<br>);</pre><p><strong>Genuinely,</strong> I felt this file is <strong>unnecessary</strong> if you are working on <strong>large</strong> applications where for each feature you need to create the <strong>selectors</strong> to get the data. So, that was the main <strong>unwanted</strong> and <strong>undesired</strong> in our code.</p><p>I almost <strong>conceded defeat</strong> and <strong>stopped trying</strong> to use the Ngrx, but I found something interesting on the <strong>Ngrx Official page: Link: </strong><a href="https://ngrx.io/guide/store/action-groups.">https://ngrx.io/guide/store/action-groups.</a></p><h3>Conquering Boilerplate with createFeature and ActionsGroup</h3><p><strong>ActionsGroups</strong> we have already discussed so now we are going to talk about the key feature of Ngrx is<strong> createFeature.</strong></p><p><strong>createFeature</strong> takes two important inputs: <strong>featrueKeyName </strong>and<strong> Reducers </strong>and <strong>Generate</strong> the <strong>Selectors.</strong> Yeah, you heard right. This is true. Extra code is not required for the <strong>Selectors,</strong> it is the <strong>Out Of the Box feature.</strong></p><p>Just think about this how much boilerplate code will reduce here, then I got excited to use this, Just check the Below code.</p><pre>// Import necessary functions and types from @ngrx/store<br>import { createFeature, createReducer, on } from &#39;@ngrx/store&#39;;<br>// Import the actions related to file upload<br>import { FileUploadActions } from &#39;./actions&#39;;<br><br>// Define the shape of the file upload state<br>export interface FileUploadState {<br>  file: string | null;<br>  progress: number;<br>  result: any | null;<br>  error: any | null;<br>  response:any<br>}<br><br>// Define the initial state for the file upload feature<br>export const initialState: FileUploadState = {<br>  file: null,<br>  progress: 0,<br>  result: null,<br>  error: null,<br>  response:null<br><br>};<br><br>// Create a feature for the file upload, providing a unique key and reducer<br>const FileUploadFeature = createFeature({<br>  name: &#39;fileUploadFeatureKey&#39;, // Unique key for the feature<br>  reducer: createReducer(<br>    initialState, // Initial state for the feature<br>    // Define reducer logic for different actions using the &#39;on&#39; function<br>    on(FileUploadActions[&#39;[FileUpload]UploadRequest&#39;], (state,{file}) =&gt; {<br>      // Reset the state when an upload request is made<br>      return {<br>        ...state,<br>        file<br><br>      };<br>    }),<br>    on(<br>      FileUploadActions[&#39;[FileUpload]UploadProgress&#39;],<br>      (state, { progress }) =&gt; {<br>        // Update the state with the progress when upload progress action is dispatched<br>        return {<br>          ...state,<br>          progress,<br>        };<br>      },<br>    ),<br>    on(FileUploadActions[&#39;[FileUpload]UploadSuccess&#39;], (state, { result }) =&gt; {<br>      // Update the state with the result when upload success action is dispatched<br>      return {<br>        ...state,<br>        result,<br>      };<br>    }),<br>    on(FileUploadActions[&#39;[FileUpload]UploadFailure&#39;], (state, { error }) =&gt; {<br>      // Update the state with the error when upload failure action is dispatched<br>      return {<br>        ...state,<br>        error,<br>      };<br>    }),<br><br>    on(FileUploadActions[&#39;[FilesFetched]RequestToFetchTheFiles&#39;], (state) =&gt; {<br>      // Update the state with the error when upload failure action is dispatched<br>      return {<br>        ...state,<br>      };<br>    }),<br>     on(FileUploadActions[&#39;[FilesFetched]SuccessToFetchTheFiles&#39;], (state,{response}) =&gt; {<br>      // Update the state with the error when upload failure action is dispatched<br>      return {<br>        ...state,<br>        response:response[&#39;body&#39;]<br>      };<br>    }),<br>     on(FileUploadActions[&#39;[FilesFetched]FailureToFetchTheFiles&#39;], (state,{error}) =&gt; {<br>      // Update the state with the error when upload failure action is dispatched<br>      return {<br>        ...state,<br>        error<br>      };<br>    }),<br>  ),<br>});<br><br>// Destructure the properties of the created feature for easier usage<br>export const {<br>  name: fileUploadFeatureKey, // Unique key for the feature<br>  reducer: FileUploadReducer, // Reducer function for the featur<br>  selectError,<br>  selectFile,<br>  selectResult,<br>  selectProgress,<br>  selectResponse<br>} = FileUploadFeature;</pre><p>Here, we have combined reducers and selectors. indeed <strong>Selectors</strong> were auto-generated here.</p><p>How you will use this Reducer in Store, so just look at the code and we are providing the <strong>fileUploadFeatureKey</strong> and Our <strong>FileUploadReducer</strong> to the <strong>StoreModule</strong></p><pre> {<br>    path: AppPath.UPLOADFILE,<br>    component: UploadFileComponent,<br>    providers: [<br>      importProvidersFrom(<br>        StoreModule.forFeature(fileUploadFeatureKey, FileUploadReducer),<br>        EffectsModule.forFeature([UploadEffects]),<br>      ),<br>    ],<br>  }</pre><p>This post tackles the common issue of boilerplate code during NgRx integration in <strong>Angular apps</strong>. The post outlines the issues developers face in adopting NgRx, specifically the surplus of boilerplate, and introduces NgRx ActionsGroups and createFeature as effective solutions.</p><p>Demonstrating the streamlined code achieved through <strong>the acceptances of ActionsGroups</strong> and createFeature. The discussion covers the challenges in defining distinct <strong>Actions</strong> and <strong>Reducers</strong>, emphasizing the need for manipulation without efficient tools. The post highlights the drawbacks of manual Selector creation, particularly in larger applications.</p><p>The turning point comes with the discovery of createFeature on the NgRx official page, presenting a solution that significantly reduces boilerplate code. Expresses excitement about the newfound simplicity and elegance in the code, concluding with a positive note — “Happy NgRx.” Overall, the post offers valuable insights into overcoming NgRx integration challenges and showcases practical solutions to enhance the development experience in <strong>Angular applications.</strong></p><h3><strong>Happy NgRx </strong>👏</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ea574a63e58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generic Rxjs Raised/Subscription event Angular (Typescript)]]></title>
            <link>https://medium.com/@kumarsehdev600/generic-rxjs-raised-subscription-event-angular-typescript-7257f91e22f?source=rss-a16534ecee82------2</link>
            <guid isPermaLink="false">https://medium.com/p/7257f91e22f</guid>
            <dc:creator><![CDATA[Sehdev Kumar]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 05:29:57 GMT</pubDate>
            <atom:updated>2023-03-24T05:29:57.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gABeP-qkqxfkWQxAhp7Diw.jpeg" /></figure><p>Hi, all</p><p>Let’s discuss first what is a use case of <strong>“Generic Rxjs Raised/Subscription”</strong> then we will move to the actual solution.</p><blockquote>The use case of Generic RxJS subscription/raising is to provide a way to handle different types of events in a modular and flexible way. By defining a generic event system using RxJS, events can be emitted and subscribed to across different parts of the application, without having to tightly couple them to each other.</blockquote><blockquote>For example, suppose you have an application with multiple components that need to communicate with each other. Instead of directly calling methods on other components, which can lead to <strong>tight coupling</strong> and <strong>spaghetti code</strong>, you can use a generic event system based on RxJS. Each component can raise events that are subscribed to by other components, and vice versa, without having to know about the implementation details of the other components.</blockquote><blockquote>This allows for a more modular and flexible architecture, where components can be added, removed, or modified without affecting the rest of the application. It also enables better code reusability, as events can be raised and handled in a generic way, without having to duplicate code across different components.</blockquote><blockquote>Overall, Generic RxJS subscription/raising provides a powerful and flexible way to handle events in modern web applications, allowing for more modular, maintainable, and scalable code.</blockquote><p>We will take one example use case that will clear your doubts, why and how?</p><p>let&#39;s assume we have two<strong> components(Alpha &amp; Beta) </strong>in angular which are not parent and child, then how they will share data of course will use Rxjs subjects in this case.</p><p>let&#39;s say component “Alpha” has some buttons that are for different purposes, and whenever you clicked the particular button some actions happened in component “Beta”, as you can see below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*8UP1w_CuCmuBxkYlnOyfUg.png" /></figure><p>what would you like to do in this case, should we create 3 — rxjs subjects because every action has distinct object Data So normally we will use the same rxjs subject to share data, and now “Generic Subject” comes into the picture.</p><p>We Need to Create a Generic Class, a Service that will hold the Information, like Subject, Data, and Type, also need to create the enum and interface.</p><p>First, the interface GenericEvents is defined with two properties: eventType which is of type GenericEventType (an enum defined later in the code), and eventData which is of type any. This interface can be used to define objects that contain an event type and some data related to that event.</p><p>The GenericEventType enum is then defined with three properties: PROFILE, SETTINGS, and ABOUT. Each of these properties is set to a string value that describes a different kind of event.</p><p>This code defines an interface <strong>`GenericEvents`</strong> which has two properties: <strong>`eventType`</strong> of type <strong>`GenericEventType` </strong>and <strong>`eventData`</strong> of type <strong>`any`</strong>. <strong>`GenericEventType`</strong> is an enum with three possible values: <strong>`PROFILE_CLICKED`, `SETTINGS_CLICKED`</strong>, and <strong>`ABOUT_CLICKED`</strong>. The <strong>`WHGenericEventClass`</strong> is a class that implements the <strong>`GenericEvents`</strong> interface and has <strong>`eventType`</strong> and <strong>`eventData`</strong> properties. The <strong>`CommonService`</strong> class is decorated with <strong>`@Injectable`</strong> and defines a <strong>`genericSubject` </strong>property which is an instance of the <strong>`Subject` </strong>class that emits instances of `WHGenericEventClass`. Overall, this code defines a generic event system that can be used to emit and handle different types of events across an application. The <strong>`CommonService`</strong> class serves as a central hub for emitting events, while other parts of the application can subscribe to these events and react to them accordingly.</p><pre>export interface GenericEvents {<br>  eventType: GenericEventType<br>  eventData: any<br>}<br><br>export enum GenericEventType {<br>  PROFILE = &#39;PROFILE_CLICKED&#39;,<br>  SETTINGS = &#39;SETTINGS_CLICKED&#39;,<br>  ABOUT = &#39;ABOUT_CLICKED&#39;<br>}<br><br><br>export class WHGenericEventClass implements GenericEvents {<br>  eventType: GenericEventType;<br>  eventData: any;<br>}<br><br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class CommonService {<br>    <br>  genericSubject: Subject&lt;WHGenericEventClass&gt; = new Subject();<br><br>}</pre><blockquote>This code defines an `AlphaComponent` class with three methods, `onProfileClicked`, `onSettingClicked`, and `onAboutClicked`, which emit different types of events using the `CommonService` injected via the constructor. Each method creates a `data` object with specific properties related to the event being emitted. It then creates a new instance of `WHGenericEventClass` and assigns the `eventType` and `eventData` properties based on the event being emitted. Finally, it calls the `next` method of the `genericSubject` property of the `CommonService` to emit the event. Overall, this code provides a way for `AlphaComponent` to emit different types of events based on user interactions, and these events can be subscribed to by other parts of the application to react accordingly.</blockquote><blockquote><strong>Alpha Component</strong></blockquote><pre>export class AlphaComponent {<br><br>  <br>  constructor(private cs:CommonService) {}<br><br>  <br>  // On Profile Clicked<br>  <br>  onProfileClicked() {<br>     const data = {<br>        name:&#39;xyz&#39;,<br>        address:&#39;india&#39;<br>     } <br>     const genericEvent = new WHGenericEventClass();<br>     genericEvent.eventData = data;<br>     genericEvent.eventType = GenericEventType.PROFILE_CLICKED;<br>     this.cs.genericSubject.next(genericEvent)<br>  }<br><br>  // On Settings Clicked<br>   onSettingClicked() {<br>      const data = {<br>        enableDarkTheme:false,<br>        changeEmail: true,<br>        .....<br>     } <br>     const genericEvent = new WHGenericEventClass();<br>     genericEvent.eventData = data;<br>     genericEvent.eventType = GenericEventType.SETTINGS_CLICKED;<br>      this.cs.genericSubject.next(genericEvent)<br>    }<br><br>  // On About Clicked<br>   onAboutClicked() {<br>      <br>     const data = {<br>        about:&#39;xyz...........&#39;<br>        location:&#39;..........&#39;<br>     } <br>     const genericEvent = new WHGenericEventClass();<br>     genericEvent.eventData = data;<br>     genericEvent.eventType = GenericEventType.ABOUT_CLICKED;<br>     this.cs.genericSubject.next(genericEvent)<br><br>  }<br><br>}</pre><blockquote>This code defines a `BetaComponent` class that implements the `OnInit` interface and subscribes to the `genericSubject` property of the `CommonService` injected via the constructor. In the `ngOnInit` method, the `genericSubject` is subscribed to using the `subscribe` method of the `Subject` class. Inside the subscription callback function, a `switch` statement is used to handle the different types of events emitted by the `AlphaComponent`. Depending on the `eventType` of the event, different actions can be taken, such as updating the UI, making API calls, or dispatching other events. Overall, this code provides a way for `BetaComponent` to react to different types of events emitted by the `AlphaComponent`, allowing for a modular and flexible application architecture.</blockquote><blockquote><strong>Beta Component</strong></blockquote><pre>This code defines an `AlphaComponent` class with three methods, `onProfileClicked`, `onSettingClicked`, and `onAboutClicked`, which emit different types of events using the `CommonService` injected via the constructor. Each method creates a `data` object with specific properties related to the event being emitted. It then creates a new instance of `WHGenericEventClass` and assigns the `eventType` and `eventData` properties based on the event being emitted. Finally, it calls the `next` method of the `genericSubject` property of the `CommonService` to emit the event. Overall, this code provides a way for `AlphaComponent` to emit different types of events based on user interactions, and these events can be subscribed to by other parts of the application to react accordinglyexport class BetaComponent  implements OnInit {<br>  <br> constructor(private cs:CommonService) {}<br><br>  ngOnInit() {<br>     <br>    // Subscribe the Generic Subject<br>    <br>    this.cs?.genericSubject?.subscribe((event)=&gt; {<br>           <br>         switch(event?.eventType) {<br>              <br>          case  GenericEventType.SETTINGS_CLICKED:<br>              // Do somethings......<br><br>          case GenericEventType.ABOUT_CLICKED:<br>            // Do somethings...<br><br>           case GenericEventType.PROFILE_CLICKED:<br>            // Do other stuffs.....<br><br><br>         }<br><br>    })<br>  }<br><br>}</pre><p>If you observe this given implementation you will see how the generic event fires on different actions with distinct data from the “Alpha Component” and Subscribed into the “Beta Component” with the help of “CommonService”.</p><p>you can make this more flexible and Scalable to a certain level and could use more generic actions which can help you more in terms of when your structure is flowing these patterns.</p><blockquote>Happy Generic Event</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7257f91e22f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>