<?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 Ankit kaushik on Medium]]></title>
        <description><![CDATA[Stories by Ankit kaushik on Medium]]></description>
        <link>https://medium.com/@ankit-kaushik?source=rss-65067bafe701------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z7UxKiQVt7V2lALxc7_L0Q.jpeg</url>
            <title>Stories by Ankit kaushik on Medium</title>
            <link>https://medium.com/@ankit-kaushik?source=rss-65067bafe701------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:47:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankit-kaushik/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[New Input Signal: A comprehensive comparison with the traditional Input]]></title>
            <link>https://ankit-kaushik.medium.com/new-input-signal-a-comprehensive-comparison-with-the-traditional-input-cebce92ccd96?source=rss-65067bafe701------2</link>
            <guid isPermaLink="false">https://medium.com/p/cebce92ccd96</guid>
            <category><![CDATA[signal]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Ankit kaushik]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 10:26:00 GMT</pubDate>
            <atom:updated>2025-04-13T10:26:00.835Z</atom:updated>
            <content:encoded><![CDATA[<p>Here, we are going to talk about the differences that new input signal brings as compared to the traditional Input decorator approach.</p><figure><img alt="Traditional Input vs the new input signal illustration analogy" src="https://cdn-images-1.medium.com/max/1024/1*9vIAkoLXNQgzY8h4Qiy0tw.png" /></figure><h4>Input Signal</h4><p>myInputProp = input&lt;boolean&gt;(false);</p><h4>Traditional input decorator</h4><p>@Input() myInputProp: boolean = false;</p><h4>Changing the input prop programmatically</h4><p>It is possible with the <em>traditional Input </em>but not with the new <em>input Signal</em>. I believe its better that way, enforces the unidirectional flow and declarative paradigm.</p><pre>@Input() myInputProp: boolean = false;<br><br>performUpdate() {<br>  this.myInputProp = true;<br>}</pre><pre>myInputProp = input&lt;boolean&gt;(false)<br><br>performUpdate() {<br>  // no method available to update myInputProp signal value<br>  // its not a writable signal (readonly signal within the component)<br>}</pre><p>This might also create a hurdle for you if you want to set these signal based inputs programmatically outside the template (maybe for contentChild, viewChildren or in your unit test cases).</p><h4>Derived values</h4><p>How do we have a derived value based on our input property</p><pre>@Input() username: string;<br><br>get initials(value: string) {<br>  return this.extractInitials(value);<br>}</pre><p>with input signal</p><pre>username = input&lt;string&gt;();<br><br>initials = computed(() =&gt; {<br>  return this.extractInitials(this.username());<br>});</pre><p>Using initials in the template</p><pre>&lt;p&gt; {{ initials() }} &lt;/p&gt;</pre><p>Now, with the traditional Input, the extractInitials function is gonna be invoked with each change detection cycle, whereas with the new input and computed signal approach its gonna be invoked only when the username changes (also the first time). So, you can estimate how performance intensive it could be if the derived value has a heavy computation.</p><h4>Side Effect on Input change</h4><p>With the traditional approach: Either you do it with ngOnChanges or with the getter setter approach (there are other 2 approaches too but not that popular).</p><pre>@Input() username: string;<br><br>ngOnChanges(changes: SimpleChanges) {<br>  if (changes[&#39;username&#39;]) {<br>    this.onUsernameChange(this.username); // side effect <br>  }<br>}</pre><pre>private _username: string;<br>  <br>@Input()<br>set username(value: string) {<br>  this._username = value;<br>  this.onUsernameChange(); // side effect<br>}<br>  <br>get username(): any {<br>  return this._username;<br>}</pre><p>With the new Input Signal: Angular has a dedicated API called effect</p><pre>username = input&lt;string&gt;();<br><br>constructor() {<br>  effect(() =&gt; {<br>    this.onUsernameChange(this.username()); // side effect<br>  });<br>}</pre><h4>Unit Testing Component with Input props</h4><p>If you are not having a wrapper host component for the component under test. It is fairly straightforward with the traditional Input:</p><pre>it(&#39;should set initials properly&#39;, () =&gt; {<br>  componentInstance.username = &#39;Ankit Kaushik&#39;;<br>  fixture.detectChanges();<br><br>  expect(componentInstance.initials).toBe(&#39;AK&#39;);<br>});</pre><p>with the new input signal</p><pre>it(&#39;should set initials properly&#39;, () =&gt; {<br>  fixture.componentRef.setInput(&#39;username&#39;, &#39;Ankit Kaushik&#39;);<br>  <br>  expect(componentInstance.initials()).toBe(&#39;AK&#39;);<br>});</pre><h4>Two way binding</h4><p>with the traditional approach: (not covering ngModel that comes with FormsModule )</p><pre>@Component({ selector: &#39;custom-slider&#39;, /* ... */ })<br>export class CustomSlider {<br>  @Input() value;<br><br>  // output has to be stragically named<br>  // in order to support two-way binding<br>  // `${input-name}Change`<br>  @Output() valueChange = new EventEmitter();<br>}<br><br>@Component({ template: `&lt;custom-slider [(value)]=&quot;volume&quot; /&gt;` })<br>export class MediaControls {<br>  volume = 0;<br>}</pre><p>with the new model()</p><pre>@Component({ /* ... */})<br>export class CustomSlider {<br>  // Define a model input named &quot;value&quot;.<br>  value = model(0);<br>  increment() {<br>    // Update the model input with a new value, propagating the value to any bindings.<br>    this.value.update(oldValue =&gt; oldValue + 10);<br>  }<br>}<br>@Component({<br>  /* ... */<br>  // Using the two-way binding syntax means that any changes to the slider&#39;s<br>  // value automatically propagate back to the `volume` signal.<br>  // Note that this binding uses the signal *instance*, not the signal value.<br>  template: `&lt;custom-slider [(value)]=&quot;volume&quot; /&gt;`,<br>})<br>export class MediaControls {<br>  // Create a writable signal for the `volume` local state.<br>  volume = signal(0);<br>}</pre><p>Also as of now I find this model input as a handy way to programmatically set input outside of template scope as opposed to the input signal as I mentioned before.</p><blockquote>Thats it for now, Please reach out or comment if you have any queries, feedback or want me to elaborate something in particular. Thank you!! and don’t forget to appreciate if you liked this article.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cebce92ccd96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loading State Utility in React: An Improved Approach]]></title>
            <link>https://ankit-kaushik.medium.com/loading-state-utility-in-react-an-improved-approach-3f5f9cfae4fa?source=rss-65067bafe701------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f5f9cfae4fa</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Ankit kaushik]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 18:15:14 GMT</pubDate>
            <atom:updated>2024-10-03T18:15:14.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3sAJFVgpqmir8mT290pmg.jpeg" /></figure><p>Maintaining loading states in a React application can be a challenge. Developers often resort to using flags or separate state variables for each loader, which can lead to verbose and cumbersome code. This article presents an improved approach to managing loading states in React, building upon the concepts discussed in my previous Medium article</p><p><a href="https://blog.stackademic.com/loading-state-utility-in-react-js-bde4256fa123">Loading state utility in React.js</a></p><p>The utility aims to provide a centralized and efficient mechanism for controlling and displaying loading indicators throughout the application.</p><p>This enhanced approach prioritizes <strong>targeted rendering for better performance</strong>. It introduces a <strong>notifier system</strong> based on the <strong>pub-sub </strong>design pattern that directly updates components dependent on a specific loader. This targeted approach ensures that only the necessary parts of the application re-render when a loading state changes.</p><h3>The Core Concept</h3><p>At the heart of this utility lies a map that stores loaderIds and their corresponding frequencies. The loaderId acts as a unique identifier for a specific loading state, while the frequency represents the number of asynchronous operations associated with that loader. For instance, if two API calls trigger the same &quot;global&quot; loader, the map would look like {global: 2}. Once both calls complete, the state updates to {global: 0}, indicating that the &quot;global&quot; loader is no longer active.</p><pre>// stateRef holds<br>{<br>   global: 0,<br>   users: 1<br>}</pre><h3>Building the Utility</h3><p>The utility comprises several key components:</p><ul><li><strong>LoadersContext</strong>: A React context that provides access to the loading state and the related utility functions throughout the application.</li><li><strong>LoadersProvider</strong>: A component that initializes the context, provide it globally (or whatever level you decide). It holds the loading state and provides functions to update it.</li><li><strong>triggerLoading</strong>: A function that wraps asynchronous operations and updates the loading state accordingly. It takes a function that returns a promise (deferFn) and a loaderId as arguments. It increments the frequency for the given loaderId before executing the asynchronous operation and decrements it upon completion.</li><li><strong>updateLoaders</strong>: A function that modifies the loading state. It takes a loaderId and an amount to adjust the frequency.</li><li><strong>useIsLoading</strong>: A hook that allows components to subscribe to changes in a specific loader&#39;s state. It returns a boolean value indicating whether the loader is active. This hook leverages the attachNotifier and disposeNotifier functions to register and unregister callbacks for targeted updates.</li><li><strong>useLoading</strong>: A hook that provides access to the triggerLoading function, enabling components to trigger loading states.</li><li><strong>IsLoading</strong>: A component that conditionally renders its children based on the loading state of a specific loader. It accepts a loaderId prop and only renders its children if the corresponding loader is active.</li></ul><h4>Here’s the final gist for your ongoing reference</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/475b38a7ed8ff9ee07e07471216ef708/href">https://medium.com/media/475b38a7ed8ff9ee07e07471216ef708/href</a></iframe><h3>The Notifier System</h3><p>The introduction of a notifier system is the key improvement in this version. This system allows for targeted re-renders, enhancing performance. Here’s how it works:</p><ul><li><strong>notifiersRef</strong>: This useRef hook stores a map of loaderIds to a set of callback functions (NotifierType). Each callback represents a component interested in the state of that specific loader.</li><li><strong>attachNotifier</strong>: This function adds a callback to the notifiersRef for a given loaderId.</li><li><strong>disposeNotifier</strong>: This function removes a callback from the notifiersRef for a given loaderId.</li><li><strong>Triggering Updates</strong>: Whenever updateLoaders is called, it not only updates the loading state but also iterates through the set of callbacks associated with the modified loaderId and invokes each callback. This informs the subscribed components about the state change, prompting a re-render only where necessary.</li></ul><h3>Example Usage</h3><p>To use this utility, wrap your application with the LoadersProvider component at the root level. This makes the loading state and utility functions available throughout the application.</p><p>To trigger a loading state, use the useLoading hook and call the loading function with an asynchronous operation and a loaderId. For example:</p><pre>const loading = useLoading();<br>loading(() =&gt; fetch(&#39;api/resource&#39;), &#39;myLoaderId&#39;)<br>.then(...)</pre><p>To conditionally render content based on a loading state (although you can use your own component too or however necessary) , use the IsLoading component. Provide the loaderId prop, and the component will only render its children if the corresponding loader is active. For example:</p><pre>&lt;IsLoading loaderId=&quot;myLoaderId&quot;&gt;<br>Loading...<br>&lt;/IsLoading&gt;</pre><p>The useIsLoading hook can be used within components to programmatically access the loading state for a specific loader. <strong>Try playing with in the following sandbox:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Frz6777%3Fview%3Deditor%2B%252B%2Bpreview%26module%3D%252Fsrc%252Floaders.tsx%26expanddevtools%3D1&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Frz6777&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Frz6777%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf6fc6a2124bd61c872763a6c4c827aa/href">https://medium.com/media/cf6fc6a2124bd61c872763a6c4c827aa/href</a></iframe><p>Also, if you want to look at a thorough usage you can checkout this module named react-loaders in</p><p><a href="https://github.com/ankitkaushik24/performant-projects/tree/main/src/app/react-loaders">performant-projects/src/app/react-loaders at main · ankitkaushik24/performant-projects</a></p><h3>Benefits of This Approach</h3><ul><li><strong>Centralized State Management</strong>: All loading states are managed in a single location, making it easy to track and modify them.</li><li><strong>Reduced Code Verbosity</strong>: The utility eliminates the need for multiple flags or separate state variables for each loader, resulting in cleaner and more maintainable code.</li><li><strong>Targeted Rendering</strong>: The notifier system ensures that only components that depend on a specific loader are re-rendered when its state changes, leading to improved performance.</li><li><strong>Improved Developer Experience</strong>: The utility provides a simple and intuitive API for managing loading states, making it easier for developers to implement and maintain loading indicators in their applications.</li></ul><p>This improved approach provides a robust and efficient solution for managing loading states in React applications. By leveraging a centralized context and a targeted notifier system, it simplifies the process of displaying loading indicators while optimizing performance.</p><blockquote>I hope you found this walk-through helpful. If yes, I would love to know your thoughts around it. Leaving you with a note “Share some good words”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f5f9cfae4fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regex controlled Input in React.js]]></title>
            <link>https://ankit-kaushik.medium.com/regex-controlled-input-in-react-js-8f56cf02a6ef?source=rss-65067bafe701------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f56cf02a6ef</guid>
            <category><![CDATA[util]]></category>
            <category><![CDATA[input-validation]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Ankit kaushik]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 02:25:03 GMT</pubDate>
            <atom:updated>2024-03-31T02:40:14.483Z</atom:updated>
            <content:encoded><![CDATA[<h3>Regex based controlled Input in React.js</h3><p>Isn’t it very common to have input having some restrictions, examples include:</p><ul><li>allow only at most 2 decimals in a number</li><li>only alphanumeric characters</li><li>only positive numbers</li><li>not allow trailing spaces</li><li>preventing whitespaces in the beginning</li><li>and so many patterns more.</li></ul><p>Today, we are going to build a directive / utility / High Order Component to handle such scenarios effectively with ease which depicts extensibility and robustness.</p><figure><img alt="Hands on Keyboard and floating blurred characters" src="https://cdn-images-1.medium.com/max/1024/1*EHnWbI4IcC6jmAZCxjIU1Q.jpeg" /><figcaption>Typing the input on Keyboard</figcaption></figure><h4>How are we going to determine whether the input text is valid as per the provided pattern</h4><pre>const isValid = (pattern: string, text) =&gt; {<br>  return new RegExp(pattern).test(text);<br>}</pre><p>For the common patterns in your application you can also have it defined to be reused. Something like this:</p><pre>const categories = {<br>  decimals_2: &#39;^[0-9]+(\\.[0-9]{0,2}){0,1}$&#39;,<br>  numbers: &#39;^[0-9]d{9}&#39;<br>};<br><br>// passing defined one or the custom<br>const isValid = (pattern: string, text) =&gt; {<br>  return new RegExp(categories[pattern] || pattern).test(text);<br>}</pre><p>Along with the pattern, let us also include the support for a callbackFn the user could provide optionally to additionally run some checks on the newValue for its validity.</p><pre>const isValid = <br>  (pattern, text, isInvalidFn = (newValue) =&gt; false) =&gt; {<br>    if (isInvalidFn(text)) {<br>      return false;<br>    }<br><br>    return new RegExp(categories[pattern] || pattern).test(text);<br>}</pre><p>The most common strategy that could come to you is <strong>preventDefault</strong> on <strong>keydown</strong> event if it doesn’t match the pattern, and you are brilliant if that hit you. Here, we are gonna leverage the same technique to build our utility.</p><pre>const onKeyDown = (event) =&gt; {<br>  // it is not event.target.value<br>  // as that&#39;s gonna be the old value<br>  const value = ?? <br><br>  if (!isValid(value)) {<br>    event.preventDefault();<br>  }<br>}</pre><p>But! Wait a second. What if the user hitting enter / return / backspace / or any meta key? Those keystrokes should pass through as it doesn’t affect our input. Lets handle that:</p><pre>const shouldPass = (e: KeyboardEvent) =&gt; {<br>  switch (true) {<br>    case e.metaKey:<br>    case e.ctrlKey:<br>    case e.altKey:<br>    case e.key?.length !== 1: return true;<br>    default: return isValidText(e, e.key, pattern);<br>  }<br>}</pre><p>Now the challenge is, <strong>how do we get the new value formed after we allow that key stroke</strong>. Here’s the algorithm, that also takes takes care of the edge case when the cursor might be in the middle of the existing value or text.</p><pre>const constructFutureValue = (event, newText = event.key) =&gt; {<br>  const start = event.target.selectionStart;<br>  const end = event.target.selectionEnd;<br>  const oldValue = event.target.value;<br><br>  const futureValue = <br>  oldValue.substring(0, start) + newText + oldValue.substring(end);<br><br>  return futureValue;<br>}</pre><p>While constructing the future value we are using selectionStart or selectionEnd to get the cursor selected range that could be available only for the text based inputs such as: text, search, URL, tel, and password. So, we might want to warn or throw an error if directive is being applied to any non text based input. I chose to do it the following way, although other ways are also possible.</p><pre>const validateInputType = (el: HTMLInputElement) =&gt; {<br>  if (typeof el.selectionStart !== &#39;number&#39;) {<br>    console.error(<br>      &#39;%c Cannot include permitInput for non-text input elements!&#39;,<br>      &#39;color: red; background: yellow; font-size: 16px;&#39;<br>    );<br>  }<br>};</pre><p>After the keydown event, shouldn’t we handle the paste as well and not allow user to paste any value that doesn’t fit the criteria. Now, we have to listen to the paste event as well, and in the handler the only change will be replacing event.key with event.clipboardData?.getData(&#39;text/plain&#39;) to get the new text fed.</p><pre>const onPaste = (event: ClipboardEvent) =&gt; {<br>  const newText = event.clipboardData?.getData(&#39;text/plain&#39;);<br><br>  const futureValue = constructFutureValue(event, newText);<br><br>  ...<br>}</pre><h3>For React.js enthusiasts, You could have an HOC with these superpowers</h3><pre>// incase you want to attach just the props<br>export function permitInputProps(pattern, isInvalidFn = (value: string) =&gt; false) {<br>    return {<br>	type: &#39;text&#39;,<br>	onKeyDown: attachKeyDown(pattern, isInvalidFn),<br>	onPaste: attachPaste(pattern, isInvalidFn)<br>    };<br>}<br><br>export function withPermitInput(<br>	InputComponent,<br>	pattern,<br>	isInvalidFn = (value: string) =&gt; false<br>) {<br>    return (props) =&gt; (<br>        &lt;InputComponent<br>	    type=&quot;text&quot;<br>	    {...props}<br>	    {...permitInputProps(pattern, isInvalidFn)}<br>	/&gt;<br>    );<br>}</pre><h4>Here is the Final Gist</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e7b7328f431288d92438e7a5daffa66/href">https://medium.com/media/3e7b7328f431288d92438e7a5daffa66/href</a></iframe><h4>You can see it in action here:</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-li9vds%3Fembed%3D1%26file%3Dsrc%252FApp.js&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-li9vds%3Fembed%3D1%26file%3Dsrc%252FApp.js&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-li9vds%2Fb888255c02faf480e787b8d6463c1786&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/036645683a71b474c6f06aa2abec232e/href">https://medium.com/media/036645683a71b474c6f06aa2abec232e/href</a></iframe><p>I’ll be glad if you found it helpful. Thanks for reading, stay tuned for more of such content and help spread the good words.</p><blockquote>Quality is not an act, it is a habit ~ Aristotle</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f56cf02a6ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loading state utility in React.js]]></title>
            <link>https://blog.stackademic.com/loading-state-utility-in-react-js-bde4256fa123?source=rss-65067bafe701------2</link>
            <guid isPermaLink="false">https://medium.com/p/bde4256fa123</guid>
            <category><![CDATA[loading]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[utilities]]></category>
            <dc:creator><![CDATA[Ankit kaushik]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 13:46:05 GMT</pubDate>
            <atom:updated>2023-09-05T03:34:56.085Z</atom:updated>
            <content:encoded><![CDATA[<h3>Loading State Utility in React</h3><h4>Manage your loaders like a pro</h4><p>Maintaining a flag or having to maintain separate individual state for showing the user some animation while your application is busy fetching some data might be too verbose and cumbersome. What if we could manage several loading states with an effective utility requiring minimal input from the developer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8Gl4eNgXaEKFdmTei7GHA.png" /></figure><h3>The Underlying Concept to build upon</h3><p>Maintain a map to hold the loaderIds (which loader to trigger) and their respective frequency(amount) indicating the number of async operations pending to be completed. Example: If two API calls are happening triggering the same loader (namely `global`) then our map should look like {global: 2} and after both got completed the state should be {global; 0} indicating that the global loader is off now. We could rely upon this state (which we are gonna provide at the root level encouraging single source of truth) to determine the loading state of any loader within the application.</p><h3>Utility function which could alter this state</h3><pre>function updateLoaders(loaderId: string, amount: number) {<br>    loadersState = {<br>      ...loadersState,<br>      [loaderId]: (loaders[loaderId] || 0) + amount,<br>    }<br>}</pre><p>Exposing utility function to wrap the promise and update loaders accordingly</p><pre>function loading&lt;T&gt;(deferFn: () =&gt; Promise&lt;T&gt;, loaderId: string) {<br>    updateLoaders(loaderId, 1)<br>    return deferFn().finally(() =&gt; {<br>      updateLoaders(loaderId, -1);<br>  });</pre><p>We should be able to use this function as utility to trigger loading states across the application like:</p><pre>loading(() =&gt; fetch(&#39;/api/call&#39;), &#39;loaderId&#39;).then(res =&gt; res.json())</pre><h3>Hooking this concept into the React Ecosystem</h3><p>Now we have laid down the fundamental building blocks (but that’s still scattered ) to construct the utility to manage the Loaders state. Its time to encapsulate all this within the React Ecosystem.</p><h4>For holding the loaders and their amount (frequency)</h4><pre>const [state, setState] = useState&lt;Record&lt;string, number&gt;&gt;({});</pre><h4>For updating this state</h4><pre>function triggerLoading&lt;T&gt;(deferFn: () =&gt; Promise&lt;T&gt;, loaderId: string) {<br>    updateLoaders(loaderId, 1)<br>    return deferFn().finally(() =&gt; {<br>      updateLoaders(loaderId, -1);<br>  });<br>}<br><br>function updateLoaders(loaderId: string, amount: number) {<br>   setState(loaders =&gt; ({<br>     ...loaders,<br>     [loaderId]: (loaders[loaderId] || 0) + amount,<br>   }))<br>}</pre><p>Using the context API we need to provide this state (holding the active loaders) and an exposed function to update it. Encapsulating all these:</p><pre>const LoadersContext = createContext&lt;{loading: LoadingType, state: Record&lt;string, number&gt;}&gt;({});<br><br>export function LoadersProvider({ children }: {children: React.ReactNode}) {<br>  const [state, setState] = useState&lt;Record&lt;string, number&gt;&gt;({});<br>  const loading = useCallback(triggerLoading, []);<br><br>  function triggerLoading&lt;T&gt;(deferFn: () =&gt; Promise&lt;T&gt;, loaderId: string) {<br>    updateLoaders(loaderId, 1)<br>    return deferFn().finally(() =&gt; {<br>      updateLoaders(loaderId, -1);<br>  });<br>    <br>  }<br><br>  function updateLoaders(loaderId: string, amount: number) {<br>    setState(loaders =&gt; ({<br>      ...loaders,<br>      [loaderId]: (loaders[loaderId] || 0) + amount,<br>    }))<br>  }<br><br>  return (<br>    &lt;LoadersContext.Provider value={{state, loading}}&gt;<br>      {children}<br>    &lt;/LoadersContext.Provider&gt;<br>  );<br>}</pre><h4>Provide it at the root:</h4><pre>&lt;LoadersProvider&gt;<br>  &lt;App /&gt;<br>&lt;/LoadersProvider&gt;</pre><p>Also, exposing a couple of abstractions:</p><pre>function useIsLoading(loaderId: string): boolean {<br>  const {state} =  useContext(LoadersContext);<br>  return useMemo(() =&gt; state[loaderId] &gt; 0, [loaderId, state]);<br>}<br><br>export default function IsLoading({loaderId, children}: {loaderId: string, children: any}) {<br>    const isLoading = useIsLoading(loaderId);<br>    return isLoading &amp;&amp; children;<br>}</pre><p>Wrap your loader inside IsLoading providing an identifier</p><pre>&lt;IsLoading loaderId=&quot;myLoaderId&quot;&gt;<br>  Loading...<br>&lt;/IsLoading&gt;</pre><p>and with the help of this final abstraction:</p><pre>export function useLoading() {<br>  const {loading} = useContext(LoadersContext);<br>  return loading;<br>}</pre><p>trigger it like a boss</p><pre>const loading = useLoading();<br><br>loading(() =&gt; fetch(&#39;api/resource&#39;), &#39;myLoaderId&#39;)<br>  .then(...)</pre><h3>Final version</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/172b64b18637fb039e92ad9c8f9904e9/href">https://medium.com/media/172b64b18637fb039e92ad9c8f9904e9/href</a></iframe><p>I hope this might have given you rich insights to building a utility to power up your application, making it easier to manage several loader’s state(on/off) and displaying dynamic skeletons, spinners, shimmers, etc to engage your user while your application fetches the data.</p><blockquote>Thanks again, If you like the content please support me by giving your valuable feedback or like(clap). Follow me for more…</blockquote><p><em>Thank you for reading until the end. Please consider following the writer and this publication. Visit </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bde4256fa123" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/loading-state-utility-in-react-js-bde4256fa123">Loading state utility in React.js</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Component switching dynamically using lazy loading in Angular templates]]></title>
            <link>https://ankit-kaushik.medium.com/component-switching-dynamically-using-lazy-loading-in-angular-templates-81f026e4b148?source=rss-65067bafe701------2</link>
            <guid isPermaLink="false">https://medium.com/p/81f026e4b148</guid>
            <category><![CDATA[code-splitting]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[load-time-optimization]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <dc:creator><![CDATA[Ankit kaushik]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 09:59:58 GMT</pubDate>
            <atom:updated>2023-03-07T09:59:58.705Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why should we load the chunk for a component that we will not render at runtime or would it make more sense to load the component chunk having the huge size to load on request and not include it in the initial load, optimizing the initial load time as well?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nb9hCn7yFZ1iIV6w" /><figcaption>Photo by <a href="https://unsplash.com/@jonasleupe?utm_source=medium&amp;utm_medium=referral">Jonas Leupe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Suppose we want to implement something like this:</p><pre>&lt;ng-container [ngSwitch]=&quot;active&quot;&gt;<br>  &lt;app-first *ngSwitchCase=&quot;&#39;first&#39;&quot;&gt;&lt;/app-first&gt;<br>  &lt;app-second *ngSwitchCase=&quot;&#39;second&#39;&quot;&gt;&lt;/app-second&gt;<br>  &lt;app-third *ngSwitchCase=&quot;&#39;third&#39;&quot;&gt;&lt;/app-third&gt;<br>  &lt;app-fourth *ngSwitchCase=&quot;&#39;fourth&#39;&quot;&gt;&lt;/app-fourth&gt;<br>&lt;/ng-container&gt;</pre><p>Based on the value held inside the variable active, we need to render only one of the components shown, or you just want to postpone the loading of a component until render.</p><p>What if we keep a map where these references are held lazily</p><pre>componentMap = {<br>   first: defer(() =&gt; import(&#39;./first.component&#39;).then(m =&gt; m.default)),<br>   second: defer(() =&gt; import(&#39;./second.component&#39;).then(m =&gt; m.default)),<br>   third: defer(() =&gt; import(&#39;./third.component&#39;).then(m =&gt; m.default)),<br>   fourth: defer(() =&gt; import(&#39;./fourth.component&#39;).then(m =&gt; m.default)),<br>}</pre><p>In case you are wondering, why did we use defer here? It will not invoke the callback function passed until the subscription. In our case, it won’t import or load the component file or class until we request that in our templates. Now, we could simply update our template to accommodate this strategy:</p><pre>&lt;ng-container *ngComponentOutlet=&quot;componentMap[active] | async&quot;&gt;&lt;/ng-container&gt;</pre><p>You can simply use this trick to make any Eagar component in your template lazy load at runtime. For demonstration purposes, I’ve assumed that you are doing it on your standalone components but ngComponentOutlet has an input to accommodate the parent module too (Not to mention, that you wouldn’t want to refer to static or eager imports to load your modules as well). You could do a lot more with this directive, for reference: <a href="https://angular.io/api/common/NgComponentOutlet">https://angular.io/api/common/NgComponentOutlet</a></p><p>I condemn this approach for your presentation components. Instead, you could use it for your container components representing any business entity segment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81f026e4b148" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maintaining your container Component state through RxAngular]]></title>
            <link>https://ankit-kaushik.medium.com/maintaining-your-container-component-state-through-rxangular-46c4bcfacfdf?source=rss-65067bafe701------2</link>
            <guid isPermaLink="false">https://medium.com/p/46c4bcfacfdf</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[component-state]]></category>
            <category><![CDATA[facade-pattern]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Ankit kaushik]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 12:02:48 GMT</pubDate>
            <atom:updated>2023-02-18T12:02:48.471Z</atom:updated>
            <content:encoded><![CDATA[<h4>We need to pay more attention to the importance of managing the component state. It doesn’t get the attention deserved.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*Fyt9Hi5lHlNP_vaJ-KBHcw.png" /></figure><p>To make your component as thin as possible I suggest abstracting your component state in a <a href="https://en.wikipedia.org/wiki/Facade_pattern">facade</a>. The basic idea here would be to inject component-level services to hold the business entity depicted in your container component.</p><p><a href="https://www.rx-angular.io/docs/state">State | RxAngular</a></p><p>Yes, we’ll be using the above library this time to showcase the same around the following use case:</p><ul><li>Rendering paginated (infinite scroll) list of open events</li><li>Rendering paginated (infinite scroll) list of closed events</li><li>Whenever the user closes any open event, add that to the closed events list with a few manipulated properties and at the same time remove it from the open events list.</li></ul><h3>Example undertaking for this article</h3><figure><img alt="demonstration of two lists namely open and closed events list which are related to each other in some way" src="https://cdn-images-1.medium.com/max/300/1*MBSIJz_da-7mtTnVzkzGeg.gif" /><figcaption>Demonstration of two lists which are related in some way</figcaption></figure><h3>State for open events</h3><pre>// state for the open events component<br>{<br>  count: number;<br>  pageNumber: number;<br>  events: IUserEvent[];<br>}</pre><h4>Defining events that need to be fetched</h4><p>Depends on the current page and the userId for which the events need to be fetched</p><pre>userEvents$ = combineLatest([<br>  this.userId$, // observable for retrieving userId<br>  this.select(&#39;pageNumber&#39;), // this is how we listen to a peice of state in RxState<br>]).pipe(<br>    switchMap(([userId, pageNumber]) =&gt;<br>      this.fetchUserEvents(userId, pageNumber) // API call to fetch user events<br>    ),<br>    map(({ data }) =&gt; data)<br>  );</pre><p>Maintaining the state of userEvents on each emitted value set</p><pre>this.connect(this.userEvents$, (oldState, newEmittedValue) =&gt; {<br>    if (oldState.pageNumber &gt; 1) { // for pagination<br>        return {<br>            events: oldState.events.concat(newEmittedValue.events),<br>        };<br>    }<br>    return value; // reset the state to the new emitted value (page 1 events)<br>});</pre><p>There’s an action as well (<strong>close these events</strong>), Let’s define that</p><pre>// Action to be fired from within the component<br>  closeEvents$$ = new Subject&lt;{<br>    eventsToClose: IUserEvent[];<br>    resolution: Record&lt;&#39;reason&#39; | &#39;note&#39;, string&gt;;<br>  }&gt;();</pre><p>Anytime selected events are closed, that makes an update API call and marks those events as closed. Also, they need to be subtracted from the open events collection. This gives birth to a related state (eventsClosed$) to listen to and it should fire after the events are closed.</p><pre>eventsClosed$ = this.closeEvents$$.pipe( // on closeEvents$$ action<br>    exhaustMap(({ eventsToClose, resolution }) =&gt;<br>      this.closeEvents(eventsToClose, resolution) // Api call to persist the change<br>    ),<br>    share()<br>  );</pre><p>Manipulate the state once the selected events are closed</p><pre>this.connect(this.eventsClosed$, (oldState, value) =&gt; {<br>      const closedEventsIdSet = value.reduce(<br>        (acc, e) =&gt; acc.add(e.id),<br>        new Set()<br>      );<br><br>      // updated state<br>      return {<br>        events: oldState.events.filter(<br>          (oEvent) =&gt; closedEventsIdSet.has(oEvent.id) === false<br>        ),<br>        count: oldState.count - value.length,<br>      };<br>    });</pre><h3>Similarly, you can form the state facade for the closed event list as well</h3><pre><br>interface ICloseEventsState {<br>  count: number;<br>  pageNumber: number;<br>  events: IUserEvent[];<br>}<br><br>enum EventStatus {<br>  open = 0,<br>  close = 1,<br>}<br><br>@Injectable()<br>export class CloseEventsState extends RxState&lt;ICloseEventsState&gt; {<br>  readonly closeEvents$ = this.select(&#39;events&#39;);<br>  readonly totalCount$ = this.select(&#39;count&#39;);<br><br>  private http = inject(HttpClient);<br>  private store = inject(Store);<br>  private userId$ = this.store.select(USER_STATE_TOKEN).pipe(<br>    map(({ id }) =&gt; id),<br>    distinctUntilChanged()<br>  );<br><br>  private userClosedEvents$ = combineLatest([<br>    this.userId$,<br>    this.select(&#39;pageNumber&#39;),<br>  ]).pipe(<br>    switchMap(([userId, pageNumber]) =&gt;<br>      this.fetchUserEvents(userId, pageNumber)<br>    ),<br>    map(({ data }) =&gt; data)<br>  );<br><br>  constructor(private openEventsState: OpenEventsState) {<br>    super();<br>    this.set({<br>      pageNumber: 1,<br>    });<br><br>    this.connect(this.userClosedEvents$, (oldState, value) =&gt; {<br>      if (oldState.pageNumber &gt; 1) {<br>        return {<br>          events: oldState.events.concat(value.events),<br>        };<br>      }<br>      return value;<br>    });<br>     <br>    // Derving state based on the event fired in facade for open event list<br>    this.connect(this.openEventsState.eventsClosed$, (oldState, value) =&gt; ({<br>      events: value.concat(oldState.events),<br>      count: oldState.count + value.length,<br>    }));<br>  }<br><br>  private fetchUserEvents(userId: string, pageNumber: number) {<br>    return this.http<br>      .get&lt;IResponse&lt;IUserEventsData&gt;&gt;(<br>        `vital/v1/users/${userId}/events`,<br>        {<br>          params: {<br>            status: EventStatus.close,<br>            pageNumber,<br>            recordPerPage: 25,<br>          },<br>        }<br>      );<br>  }<br>}</pre><p>If UserEventsComponent is your container component for both the presentation components ( OpenEventsComponent, ClosedEventsComponent). Then these states ( OpenEventsState, ClosedEventsState)have to be provided on your container component namely UserEventsComponent</p><pre>@Component({<br>  ...<br>  providers: [OpenEventsState, ClosedEventsState]<br>})<br>export class UserEventsComponent {<br>  ...<br>  ...<br>}</pre><blockquote>With this, I leave you with the task of figuring out numerous opportunities to abstract your container component state in these elegant facades.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46c4bcfacfdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic ways to conditionally lazy load a component in Angular]]></title>
            <link>https://ankit-kaushik.medium.com/dynamic-ways-to-conditionally-lazy-load-a-component-in-angular-9feb5317df2a?source=rss-65067bafe701------2</link>
            <guid isPermaLink="false">https://medium.com/p/9feb5317df2a</guid>
            <category><![CDATA[dynamic-component-loading]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <dc:creator><![CDATA[Ankit kaushik]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 02:45:59 GMT</pubDate>
            <atom:updated>2023-02-08T02:45:59.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r0z7ba-Dt36ejDaD" /><figcaption>Photo by <a href="https://unsplash.com/@priscilladupreez?utm_source=medium&amp;utm_medium=referral">Priscilla Du Preez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Use the Route factory (to utilize the DI)</h3><pre>import { ROUTES } from &#39;@angular/router&#39;;<br><br>providers: [<br>  {<br>    provide: ROUTES,<br>    useFactory: () =&gt; {<br>      const myService = inject(MyService);<br>      <br>      return getRoutes(myService); // using your service variables to manipulate routes<br>    }<br>  }<br>]</pre><p><strong>Manipulate</strong> loadComponent <strong>or</strong> loadChildren</p><pre>getRoutes = (myService) =&gt; <br>[<br>  {<br>    path: &#39;samples&#39;,<br>    loadComponent: () =&gt; <br>        myService.mode === &#39;v1&#39; <br>          ? import(&#39;./samples-v1.module&#39;) // module having default export<br>          : import(&#39;./samples-v2.module&#39;) // module having default export<br>  }<br>]</pre><p><strong>or Manipulate the</strong> matcher</p><pre>getRoutes = (myService) =&gt; <br>[<br>  {<br>    matcher: (urlSegment: UrlSegment[]) =&gt; {<br>          return myService.mode === &#39;v1&#39; &amp;&amp; url[0].path === &#39;samples&#39;<br>            ? { consumed: url }<br>            : null;<br>        },<br>    loadComponent: () =&gt; import(&#39;./samples-v1.module&#39;)<br>  },<br>  {<br>    matcher: (urlSegment: UrlSegment[]) =&gt; {<br>          return myService.mode === &#39;v2&#39; &amp;&amp; url[0].path === &#39;samples&#39;<br>            ? { consumed: url }<br>            : null;<br>        },<br>    loadComponent: () =&gt; import(&#39;./samples-v2.module&#39;)<br>  }<br>]</pre><h4>Alternatively, you can consume a map instead of if-else conditions</h4><pre>componentsMap = {<br>  v1: () =&gt; import(&#39;./samples-v1.module&#39;), // module having default export<br>  v2: () =&gt; import(&#39;./samples-v2.module&#39;).then(m =&gt; m.SampleV2Component) // not default export<br>}<br><br>export class UtilService {<br>  loadComponent(version) {<br>    return componentsMap[version]();<br>  }<br>}</pre><h3>or Load your component in the resolver</h3><pre>// Route<br>{<br>  path: &#39;samples&#39;,<br>  component: SamplesContainerComponent<br>  resolve: {<br>          componentToBeInstantiated: resolveComponentFn,<br>  },<br>}<br><br><br>// resolveComponentFn<br>const resolveComponentFn: ResolveFn&lt;unknown&gt; = (route) =&gt; {<br>  const myService = inject(MyService);<br>  const utilSerive = inject(UtilService);<br><br>  return lastValueFrom(<br>            myService.getVersion(route.queryParamMap.get(&#39;platform&#39;))<br>         ).then(v =&gt; {<br>            return utilService.loadComponent(v);<br>         })<br>}</pre><h4>Using the resolved component in the wrapper component</h4><pre>&lt;-- SamplesContainerComponent template --&gt;<br>&lt;section&gt;<br>   &lt;ng-container<br>          *ngComponentOutlet=&quot;<br>            componentToBeInstantiated;<br>            content: [[footer]]<br>          &quot;&gt;<br>   &lt;/ng-container&gt;<br>&lt;/section&gt;<br>&lt;footer #footer&gt;Content inside footer&lt;/footer&gt;</pre><h3>or Instantiating your lazy component through router-outlet</h3><pre>@Component({<br>  template: `&lt;router-outlet&gt;&lt;/router-outlet&gt;`<br>})<br>export class SamplesContainerComponent implements OnInit {<br>  @ViewChild(RouterOutlet) routerOutlet: RouterOutlet;<br>  private readonly myService = inject(MyService);<br><br>  ngOnInit(): void {<br>    this.myService.getRequiredComponent().pipe(untilDestroyed(this))<br>      .subscribe((compClass) =&gt; {<br>        this.routerOutlet.attach(<br>          this.viewContainerRef.createComponent(compClass),<br>          this.route<br>        );<br>      });<br>  }<br>}</pre><h3>Use your lazy “standalone” component in Dialog</h3><pre>openDialog(v) {<br>  this.utilService.loadComponent(v).then(m =&gt; {<br>    this.matDialog.open(m.MyComponent, {<br>      id: &#39;call&#39;,<br>      disableClose: true,<br>      data: {type: &#39;video&#39;}<br>    });<br>  });<br>}</pre><h4>You can use the same strategies even to load your remote components or modules using the module federation plugin</h4><blockquote>Thanks for being along, show some applause 👏 if liked the content and stay tuned for more of such content</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9feb5317df2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular DI system unfolded thoroughly in simple terms for practical use]]></title>
            <link>https://ankit-kaushik.medium.com/angular-di-system-unfolded-thoroughly-in-simple-terms-for-practical-use-514a1dd07336?source=rss-65067bafe701------2</link>
            <guid isPermaLink="false">https://medium.com/p/514a1dd07336</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[angular14]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Ankit kaushik]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 09:53:26 GMT</pubDate>
            <atom:updated>2023-02-05T09:53:26.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*opMIkHVLaua9vwaj" /><figcaption>Photo by <a href="https://unsplash.com/@heytowner?utm_source=medium&amp;utm_medium=referral">JOHN TOWNER</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>How do we create an instance</h4><pre>myInstance = {};<br>instanceOutOfClass = new MyClass(...dependencies);<br>property = 5;<br>member = &#39;value&#39;;</pre><p>Instances could be simply created this way but to lazily create these instances (at the time of the request, the first time it’s requested through DI), also providing dependencies to those instances at runtime easily and to facilitate providing the same (singletons) throughout the hierarchy <strong>Angular</strong> has something called <strong>Providers</strong> which we usually call <strong>Services</strong>.</p><h3>What can act as a Provider</h3><h4>Any Class having the Injectable decorator</h4><pre>@Injectable()<br>export class MyClass {}<br><br>// providing it, <br>// its instance will sit at the root unless provided again<br>@Injectable({provideIn: &#39;root&#39;})<br>export class MyClass {}<br><br>// or providing it at a particular level<br>providers: [MyClass]</pre><h4>Injection Tokens</h4><pre>export const MY_INJECTION_TOKEN = new InjectionToken&lt;MyType&gt;(&#39;my.token&#39;);<br><br>// providing it<br>export const MY_INJECTION_TOKEN = new InjectionToken&lt;MyType&gt;(&#39;my.token&#39;, {<br>  provideIn: &#39;root&#39;<br>});<br><br>// providing the blueprint too <br>// factory function will be invoked to retrieve it&#39;s instance<br>export const MY_INJECTION_TOKEN = new InjectionToken&lt;MyType&gt;(&#39;my.token&#39;, {<br>  factory: () =&gt; {<br>    const otherInstance = inject(MyOtherInstance); // utilising the DI<br>    // return () =&gt; otherInstance.token;<br>    // return otherInstance.getToken(); // sync call<br>    // return anything here you want use as an instance;<br>    return {token: otherInstance.token, id: 5};<br>  }<br>})</pre><h4>Providing the definition or value for a provider later</h4><p><a href="https://angular.io/guide/dependency-injection-providers">Angular</a></p><h4>Even string tokens can be used as a provider (NOT suggested)</h4><blockquote><strong>Better use injection token instances as it’s </strong>easier to reference and for type safety (the modern inject function keep the type definition intact).</blockquote><pre>// provide static value for this token<br>providers: [{provide: &#39;SOME_TOKEN&#39;, useValue: localStorage}]<br><br>// use MyClass to create &amp; provide an instance for this token<br>providers: [{provide: &#39;SOME_TOKEN&#39;, useClass: MyClass}]<br><br>// call myFactory function to retrieve an instance for this token<br>const myFactory = () =&gt; {x: 5, y: 8};<br>providers: [{provide: &#39;SOME_TOKEN&#39;, useFactory: myFactory}]<br><br>// use an existing instance of MyClass whenever providing for this token<br>providers: [{provide: &#39;SOME_TOKEN&#39;, useExisting: MyClass}]</pre><pre>// Using that string token in the DI<br>const myStringToken = inject(&#39;SOME_TOKEN&#39;);<br><br>// or in the constructor<br>constructor(@Inject(&#39;SOME_TOKEN&#39;) myStringToken) {}</pre><p>The first time angular finds a request for these classes to be injected, their instances are created and stored in its injector service for future references in other places.</p><pre>/**<br> * These must be called from an injection context <br> * such as a constructor, a factory function, a field initializer, <br> * or a function used with `EnvironmentInjector#runInContext<br> */<br><br>// instance is requested through DI<br>const myClassInstance = inject(MyClass);<br><br>// instance is requested through DI<br>constructor( private myClassInstance: MyClass) {}</pre><h3>Instances that angular creates from template and stores in it’s injector at that hierarchy</h3><p>Any time we place a component, directive, or pipe inside our template an instance is created for that class at that level.</p><pre><br>&lt;my-component&gt;&lt;/my-component&gt; // instance created for MyComponent Class<br><br>&lt;p myDirective&gt;&lt;/p&gt; // instance created for MyDirective Class<br><br>&lt;span&gt;{{ &#39;some content&#39; | myPipe}}&lt;/span&gt; // instance created for MyPipe Class<br><br>&lt;ng-container *ngIf=&quot;!!exp&quot;&gt;&lt;/ng-container&gt; // instance created for NgIf Class</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*H3TuYYpE2YPrQAe8NsCA9Q.png" /><figcaption>Instance classes of a few directives and components marked beside their usage in the DOM tree in Angular</figcaption></figure><p>and we can <strong>access</strong> all these instances if we are inside an injection context ( in the field initializer or constructor within your components, directives, pipes, services, etc) according to where they are placed lexically in your application hierarchy.</p><p>For example, within SideNavComponent we can get access to the instance of MainComponent (parent, lexically placed above in the hierarchy) like:</p><pre>@Component({selector: &#39;ipm-side-nav&#39;})<br>export class SideNavComponent {<br>  constructor(private mainComponent: MainComponent) {}<br>}</pre><h3>In the next blog post, we’ll cover awesome applications of using the DI in Angular applications for various use cases.</h3><blockquote>Thanks for that like by the way😉, please feel free to connect for any feedback, query or just to say Hi! on my <a href="https://www.linkedin.com/in/ankit-kaushik24/">LinkedIn</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=514a1dd07336" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One liner state management ft. RxJs]]></title>
            <link>https://ankit-kaushik.medium.com/one-liner-state-management-ft-rxjs-eb7835a13c46?source=rss-65067bafe701------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb7835a13c46</guid>
            <category><![CDATA[declarative-programming]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Ankit kaushik]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 09:01:39 GMT</pubDate>
            <atom:updated>2023-01-26T09:01:39.966Z</atom:updated>
            <content:encoded><![CDATA[<h4>Handling a use-case where we need to retrieve some data, store it and share it to multiple instances across the application</h4><figure><img alt="lightning tracks" src="https://cdn-images-1.medium.com/max/1024/1*JU2XLLeYJJYJSZrzvUvF2w.jpeg" /></figure><h4>Create a data service</h4><pre>export class DataService {<br><br>  fetchAssignedPatients = () =&gt; this.http.get(`assigned-patients-url`);<br><br>  assignedPatients$ = this.fetchAssignedPatients();<br><br>}</pre><p><strong>Subscribe</strong> to the assignedPatients$ in your components and consume it wherever you need it.</p><pre>this.dataService.assignedPatients$.subscribe((patients) =&gt; consume(patients))</pre><h3>The Problem we didn’t solve yet</h3><p>As many times as we subscribe it, we are <strong>re-fetching the data</strong>. Think for a moment what would be your approach ?</p><h3>shareReplay to your rescue</h3><pre>fetchAssignedPatients = () =&gt; this.http.get(`assigned-patients-url`).pipe(<br>        shareReplay({bufferSize: 1, refCount: true})<br>    );</pre><p>For the very first time it’s subscribed, it’ll initiate the API call and afterwards for further subscriptions made the fetched data is replayed or shared to that subscriber.</p><h4>Benefits reaped with shareReplay</h4><ul><li><strong>Not</strong> loading the data until needed</li><li>Lazy loading the data at the point of request</li><li>Succinct solution</li><li><strong>Not</strong> creating bunch of dependent states to manage</li></ul><h4>Introducing dynamic params to re-fetch the API in certain cases</h4><pre>fetchAssignedPatients = () =&gt; this.progamChange$.pipe(<br>  switchMap((programId) =&gt; this.http.get(`assigned-patients-url?${programId}`)),<br>  shareReplay({bufferSize: 1, refCount: true})<br>);</pre><p>In the above snippet we introduced a dependency of programId to our state. In a similar way the other dependencies could be clubbed together using RxJs operators to form the <strong>derived state</strong>.</p><blockquote>Thanks, stay tuned for more such things✌️</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb7835a13c46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle repeated user clicks in your Angular application]]></title>
            <link>https://ankit-kaushik.medium.com/handle-repeated-user-clicks-in-your-angular-application-f60d2317e618?source=rss-65067bafe701------2</link>
            <guid isPermaLink="false">https://medium.com/p/f60d2317e618</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ankit kaushik]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 12:06:52 GMT</pubDate>
            <atom:updated>2023-01-24T12:06:52.681Z</atom:updated>
            <content:encoded><![CDATA[<p>Many times in our application frequent user clicks within fraction of seconds could cause our functionality to behave differently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9_e2-GnNASehmt3ugusIUA.png" /><figcaption>Src: <a href="https://clarity.microsoft.com/blog/rage-clicks-user-behavior/">https://clarity.microsoft.com/blog/rage-clicks-user-behavior/</a></figcaption></figure><p>For example:</p><ul><li>Showing up a modal on click (we don’t want to trigger opening multiple modals while we operate on blocking the view)</li><li>Calling an API on click (we don’t want to trigger multiple calls within fraction of seconds)</li><li>Creating an entry and disable the button on next change detection (we don’t want to create redundant entries while we disable the button in the next tick)</li><li>and so on…</li></ul><h3>Attribute Directive to your rescue</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96b859bbb07cc885c28f59fbf238e403/href">https://medium.com/media/96b859bbb07cc885c28f59fbf238e403/href</a></iframe><h4>Throttle approach</h4><p>Consider the very first click and ignore any clicks made within N milliseconds after that</p><pre>&lt;button (click.throttle)=&quot;callMyFunction()&quot;&gt;Click me!&lt;/button&gt;</pre><h4>Debounce approach</h4><p>Consider only the last click done within N milliseconds of time</p><pre>&lt;button (click.debounce)=&quot;callMyFunction()&quot;&gt;Click me!&lt;/button&gt;</pre><blockquote>A simple yet effective heck, isn’t it. I’m always motivated and keen on such solutions, so don’t hesitate to comment or give any feedback here or on my <a href="https://www.linkedin.com/in/ankit-kaushik24/">linkedIn</a>. Thanks!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f60d2317e618" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>