<?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 Bhaskar Ray Karmakar on Medium]]></title>
        <description><![CDATA[Stories by Bhaskar Ray Karmakar on Medium]]></description>
        <link>https://medium.com/@bhaskarraykarmakar?source=rss-2df5b2bf5685------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Qjo7xHVIPnk2fHbw.jpg</url>
            <title>Stories by Bhaskar Ray Karmakar on Medium</title>
            <link>https://medium.com/@bhaskarraykarmakar?source=rss-2df5b2bf5685------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:53:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhaskarraykarmakar/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[Simplifying Form State Management in React 19 Using useActionState]]></title>
            <link>https://medium.com/@bhaskarraykarmakar/simplifying-form-state-management-in-react-19-using-useactionstate-081223e84a40?source=rss-2df5b2bf5685------2</link>
            <guid isPermaLink="false">https://medium.com/p/081223e84a40</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Bhaskar Ray Karmakar]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 09:04:59 GMT</pubDate>
            <atom:updated>2025-12-22T09:06:20.235Z</atom:updated>
            <content:encoded><![CDATA[<p>React 19 has officially introduced the <em>useActionState</em> hook, which allows for state updates based on form actions. Before React 19, this functionality was introduced experimentally as <em>useFormState</em>.</p><p>Previously, all actions like onSubmit + loading flag + useState + async handling had to be handled individually. Through <em>useActionState</em>, all these actions can be handled more efficiently. This hook enables us to update the component state in response to form submissions. It works with both the client side &amp; with the framework that supports server component/server action.</p><p><strong>API breakdown</strong></p><p>The hook accepts three parameters:</p><ol><li>actionFn: A function that runs on form submission.</li><li>Initial State: The starting value of the state. This property will also be ignored after the first invocation of the actionFn.</li><li>An optional permalink (a stable URL): The property <em>permalink</em> (a backup URL that a browser should use if JavaScript is not ready) is useful when the application is server-side rendered. Modern JavaScript often renders HTML on the server and then loads JavaScript later. In the meantime, users can click the button to submit the form. In this scenario, React must revert to the default JavaScript behavior to ensure that the application still functions correctly. Without this, the browser will reload the current page upon submission, resulting in the loss of any form state. Once the JavaScript bundle is loaded (hydrated), this parameter no longer has any effect.</li></ol><p>The <em>actionFn</em> that runs on submission accepts two parameters.</p><ol><li>prevVal: The value that is returned during the previous invocation of the form action. During the first invocation, the previous state is the same as the initial value. On the subsequent invocation, its value is the value returned during the last invocation.</li><li>formData: The standard web API. It is the object created by the browser when the form is submitted. This argument can be used to retrieve the value of the form inputs for validation and other purposes.</li></ol><p>Unlike a traditional onSubmit handler, useActionState relies on the native form action. This allows React to intercept the submission and manage pending state.</p><p>The hook returns a triplet consisting of:</p><ol><li>state: The current state, which initially will be set to the provided initial state. With each invocation, it updates to the value returned by the action function.</li><li>formAction: The function that is called when the form is submitted.</li><li>isPending: A boolean state that indicates whether the form action is still in progress, providing a straightforward way to indicate a loading state without the need for extra code. This property can be used to disable the submit button or change the button text according to the form’s state.</li></ol><p><strong>Usage</strong></p><pre>import {useActionState} from &quot;react&quot;<br><br>type InitialState = {<br>    success: boolean<br>    message: string | null<br>}<br>type VerifyUserResponse = {<br>    success: boolean<br>    status: number,<br>    message: string<br>}<br><br>export function UserRegistartion() {<br><br>    const initialState: InitialState = {<br>        success: false,<br>        message: &#39;&#39;,<br><br>    }<br><br>    async function verifyUser(prevState, formData): Promise&lt;VerifyUserResponse&gt; {<br>        const userName = formData.get(&#39;userName&#39;);<br>        const password = formData.get(&#39;password&#39;);<br>        if (!userName || !password) {<br>            return {<br>                success: false,<br>                status: 500,<br>                message: &#39;Either user name or password is missing&#39;<br>            }<br>        }<br>        await new Promise(resolve =&gt; {<br>            setTimeout(resolve, 2000)<br>        })<br><br>        return {<br>            success: true,<br>            status: 200,<br>            message: &#39;User verified&#39;,<br>        }<br>    }<br><br>    function getButtonText(state) {<br>        if (state.success) {<br>            return &#39;Submitted&#39;<br>        } else {<br>            return &#39;Verify&#39;<br>        }<br>    }<br><br>    const [state, formAction, isPending] = useActionState(verifyUser, initialState)<br><br>    return (<br>        &lt;&gt;<br>            {state.success ?<br>                &lt;div&gt;User verified successfully&lt;/div&gt; :<br>                &lt;form className=&quot;registartionForm&quot; action={formAction}&gt;<br>                    &lt;div&gt;&lt;label htmlFor=&#39;userName&#39;&gt;User name &lt;/label&gt;<br>                        &lt;input id=&#39;userName&#39; type=&#39;text&#39;<br>                               name=&quot;userName&quot;<br>                               placeholder=&#39;Enter user name&#39;/&gt;<br>                    &lt;/div&gt;<br>                    &lt;div&gt;<br>                        &lt;label htmlFor=&#39;password&#39;&gt;Password &lt;/label&gt;<br>                        &lt;input id=&#39;password&#39;<br>                               name=&#39;password&#39;<br>                               type=&#39;password&#39; placeholder=&#39;Enter password&#39;/&gt;<br>                    &lt;/div&gt;<br>                    &lt;div&gt;<br>                        {&#39;status&#39; in state &amp;&amp; state.status === 500 &amp;&amp; &lt;p className=&#39;error&#39;&gt;{state.message}&lt;/p&gt;}<br>                    &lt;/div&gt;<br>                    &lt;button type=&quot;submit&quot;&gt; {isPending ? &#39;Verifying&#39; : getButtonText(isPending)}&lt;/button&gt;<br>                &lt;/form&gt;<br>            }<br>        &lt;/&gt;<br>    )<br>}</pre><p><strong>Usage Scenario</strong></p><p>The <em>useActionState</em> hook facilitates triggering a form action and immediately updating the UI based on its return value. This hook is specifically designed to manage form submissions in React, as it combines form submission and state handling, which would otherwise require using hooks such as <em>useState</em>. Depending on business requirements, the state property can be used to display a success or error toast message. Automating the connection between form submission, action execution, and UI state, it eliminates the need to manually update the state.</p><p><strong>When NOT to use.</strong></p><p><em>useActionState</em> should not be used when the form is an interactive form like live validation per keystroke, or for a multistep wizard form and form requiring granular field-level state.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=081223e84a40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An overview of Angular toSignal]]></title>
            <link>https://medium.com/@bhaskarraykarmakar/an-overview-of-angular-tosignal-898c135fd21a?source=rss-2df5b2bf5685------2</link>
            <guid isPermaLink="false">https://medium.com/p/898c135fd21a</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[javascipt]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Bhaskar Ray Karmakar]]></dc:creator>
            <pubDate>Sun, 02 Nov 2025 16:10:17 GMT</pubDate>
            <atom:updated>2025-11-18T05:08:18.491Z</atom:updated>
            <content:encoded><![CDATA[<p>This article offers a comprehensive overview of the Angular <strong>toSignal</strong> function and its applications.</p><p>At its core, Angular <strong>toSignal</strong> serves as a mechanism to convert an RxJS observable into a signal value. It can process any data stream, including HTTP requests, WebSocket communications, or intricate user interactions, and represents the latest value as a signal.</p><p><strong>toSignal</strong> is eagerly loaded, subscribing immediately to the provided observable and generating a readable signal. One of the key advantages of utilizing <strong>toSignal</strong> is its automatic unsubscription from the observable when the component or service is destroyed.</p><p>The <strong>toSignal</strong> function features 3 overloads that allow for greater control over the behavior and type of the resulting signal.</p><ol><li>The basic conversion has no initial value.</li></ol><pre>function toSignal&lt;T&gt;(source: Observable&lt;T&gt;): Signal&lt;T | undefined&gt;;<br><br>// This is the same as above, just with explicit default options<br>function toSignal&lt;T&gt;(<br>  source: Observable&lt;T&gt;,<br>  options: { initialValue?: undefined; requireSync?: false }<br>): Signal&lt;T | undefined&gt;;</pre><p>In this case, <em>toSignal</em> returns <em>undefined</em>, because when it is created, it has no value. The data arrives asynchronously &amp; it will be <em>undefined</em> until the source observable emits the first value.</p><p>A basic example of the usage of toSignal.</p><pre>export class App {<br>  private readonly coreService = inject(CoreService);<br>  data = toSignal(<br>    this.coreService.getTenderList().pipe(map((value:TenderApiResponse) =&gt;{<br>      return value.data.map((item:TenderData)=&gt;{<br>       const {id,title,awarded,awarded_currency,description} = item;<br>       return {<br>        id,title,awarded,awarded_currency,description<br>       }<br>     })<br>    }))<br>  );<br>}</pre><pre>@if (data() === undefined){<br>  &lt;span&gt;Loading...&lt;/span&gt;<br>} @else {<br>  @for (dt of data();track dt.id){<br>    &lt;div&gt;{{dt.title}}&lt;/div&gt;<br>  }<br>}</pre><p>2. Providing an initialValue</p><p>To eliminate the <em>undefined</em> state, the <em>toSignal</em> function also accepts an initial value.</p><pre>function toSignal&lt;T, U extends T&gt;(<br>  source: Observable&lt;T&gt;,<br>  options: { initialValue: U; requireSync?: false }<br>): Signal&lt;T | U&gt;;</pre><p>This is the most common way of using the <em>toSignal</em>, which also eliminates the <em>undefined</em> state. The signal can be initialized with an empty array [], an empty object {}, or a null value to signify the loading state.</p><p>In the example below, an empty array is passed. In this context, the length of the signal&#39;s output is checked in the HTML to determine the loading state.</p><pre>  data = toSignal(<br>    this.coreService.getTenderList()<br>      .pipe(map(({data}:TenderApiResponse) =&gt;<br>      data.map(({id,title,awarded,awarded_currency,description}:TenderData)=&gt;{<br>       return {<br>        id,<br>         title,<br>         awarded,<br>         awarded_currency,<br>         description<br>       }<br>     })<br>    )),{initialValue: []} // initial value<br>  );</pre><pre>@if (data().length === 0){<br>  &lt;span&gt;Loading...&lt;/span&gt;<br>} @else {<br>  @for (dt of data();track dt.id){<br>    &lt;div&gt;{{dt.title}}&lt;/div&gt;<br>  }<br>}</pre><p>3. The Synchronous Requirement: requireSync</p><p>This overload is used when working with an observable that will emit a value immediately upon subscription.</p><pre>function toSignal&lt;T&gt;(<br>  source: Observable&lt;T&gt;,<br>  options: { requireSync: true }<br>): Signal&lt;T&gt;;</pre><p><em>option.requiredSync:true</em> is an asserion which tells <em>toSignal</em> to expect a value. If the observable does not emit synchronously it will throw an error.</p><p>The source can be an observable that emit synchronously for example <em>of()</em>, <em>startWith()</em> or <em>BehaviourSubject</em>.<br>In the example a <em>BehaviourSubject</em> is because it holds a value and emits it instantly.</p><pre>export class App {<br>  private readonly coreService = inject(CoreService);<br>  public prefs:Signal&lt;{theme:string}&gt; = <br>         toSignal(this.coreService.userPrefs$,{requireSync:true})<br>}<br><br>// in the CoreService file<br>private userPrefs = new BehaviorSubject({theme:&#39;dark&#39;});<br>public userPrefs$ = this.userPrefs.asObservable();</pre><p>Note that in this case, the output signal value cannot be <em>undefined</em>. Since the <em>requiredSync</em> is used, it is guaranteed to have a value immediately.</p><h4>Unit testing toSignal implementation using Jest</h4><pre>import {ComponentFixture, TestBed} from &#39;@angular/core/testing&#39;;<br>import {provideHttpClientTesting} from &#39;@angular/common/http/testing&#39;;<br>import {App} from &#39;./app&#39;;<br>import {provideHttpClient} from &#39;@angular/common/http&#39;;<br>import {BehaviorSubject} from &#39;rxjs&#39;;<br>import {TenderApiResponse} from &#39;./model/tender&#39;;<br>import {CoreService} from &#39;./core.service&#39;;<br><br>describe(&#39;App&#39;, () =&gt; {<br>  let component: App;<br>  let fixture: ComponentFixture&lt;App&gt;;<br>  const mockApiResponse: TenderApiResponse = {<br>    page_count: 1,<br>    page_number: 1,<br>    page_size: 1,<br>    total: 1,<br>    data: [<br>      {<br>        id: &#39;tender-1&#39;,<br>        title: &#39;Tender 1&#39;,<br>        awarded: [],<br>        date: &#39;&#39;,<br>        deadline_date: &#39;&#39;,<br>        category: &#39;&#39;,<br>        description: &#39;&#39;,<br>        phase: &#39;&#39;,<br>        phase_en: &#39;&#39;,<br>        place: &#39;&#39;,<br>        sid: &#39;&#39;,<br>        eid: &#39;&#39;,<br>        awarded_value: &#39;&#39;,<br>        awarded_currency: &#39;&#39;,<br>        awarded_value_eur: &#39;&#39;,<br>        purchaser: {<br>          id: 0,<br>          sid: &#39;&#39;,<br>          name: &#39;&#39;,<br>        },<br>        type: {<br>          id: &#39;&#39;,<br>          name: &#39;&#39;,<br>          slug: &#39;&#39;,<br>        },<br>      },<br>    ],<br>  };<br><br>  let mockTenderSubject: BehaviorSubject&lt;TenderApiResponse&gt;;<br><br>  beforeEach(async () =&gt; {<br>    mockTenderSubject = new BehaviorSubject&lt;TenderApiResponse&gt;({<br>      data: [],<br>      page_count: 0,<br>      page_number: 0,<br>      page_size: 0,<br>      total: 0,<br>    });<br><br>    await TestBed.configureTestingModule({<br>      imports: [App],<br>      providers: [<br>        provideHttpClient(),<br>        provideHttpClientTesting(),<br>        {<br>          provide: CoreService,<br>          useValue: {<br>            userPrefs$: new BehaviorSubject({ theme: &#39;light&#39; }).asObservable(),<br>            getTenderList: () =&gt; mockTenderSubject.asObservable(),<br>          },<br>        },<br>      ],<br>    }).compileComponents();<br>    fixture = TestBed.createComponent(App);<br>    component = fixture.componentInstance;<br>  });<br><br>  it(&#39;should create the app&#39;, () =&gt; {<br>    expect(component).toBeTruthy();<br>  });<br><br>  describe(&#39; toSignal unit tests&#39;, () =&gt; {<br>    it(&#39;data signal should be initially empty array&#39;, () =&gt; {<br>      expect(component.data()).toEqual([]);<br>    });<br>    it(&#39;should contain the latest value&#39;, () =&gt; {<br>      mockTenderSubject.next(mockApiResponse);<br>      expect(component.data().length).toEqual(1);<br>    });<br>    it(&#39;should initialize `pref` signal synchronously&#39;, () =&gt; {<br>      expect(component.prefs().theme).toEqual(&#39;light&#39;);<br>    });<br>  });<br>});</pre><h4>Limitation of toSignal</h4><p>This automatic cleanup mechanism operates only within the Angular context, such as a component or injector. Memory leaks will occur if used outside the injector context.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=898c135fd21a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>