blazorblazor-server-side.net-9.0

How can I ensure immediate navigation to the Products page with a "Loading" label displayed while awaiting API data in a Blazor Server app?


I have a Blazor webapp (.net 9 template) with interactive rendermode set to Server. I have a home page and Products page. In Products page, it calls API endpoint on OnInitializedAsync() method and I put a delay on it Task.Delay(1000).Wait() just to simulate. I also put streamrendering with Loading label in Products. From Home page, I click Products page but because of the delay, I am at the home page for 2 seconds when I have already clicked Products page. I am expecting that I will be redirected to Products page and the Loading label will appear. How do I handle it in the best way?


Solution

  • Using Task.Delay(1000).Wait() will synchronously block the thread and the page will be "stuck" while waiting for the task to complete.

    After replacing it with await Task.Delay(1000), the UI can remain responsive, and the waiting process is asynchronous and does not block rendering.