The Blazor Weather Component
The Weather.razor component serves as a practical example of how Blazor handles data fetching and display. Unlike the Counter component, which focuses on user interactivity (clicks), the Weather component focuses on data delivery and perceived performance.
1. Stream Rendering: The Core Concept
At the very top of the file, we see a specific attribute that defines the component's behavior:
By default, components in the Blazor Web App template use Server-Side Rendering (SSR). Normally, SSR waits for all asynchronous tasks to complete before sending any HTML to the browser. This can result in a blank screen if the data takes a long time to load.
Stream Rendering changes this workflow:
- Initial Paint: The server sends the initial HTML immediately (e.g., the page title and the "Loading..." message), even while the data is still being fetched.
- Streaming Updates: Once the asynchronous task (fetching weather data) is complete, the server sends the remaining HTML (the weather table) to the same response stream.
- Result: The browser updates the page automatically. The user sees the layout instantly, leading to a better User Experience (UX), without needing the complexity of a SignalR connection or a full WebAssembly download.
2. Managing UI State with Razor
The HTML section demonstrates how Razor syntax handles state changes gracefully. It uses a standard C# if/else block to determine what to render:
- Loading State: When the page first loads, the
forecastsvariable isnull. The user sees the "Loading..." message. - Data State: Once the data arrives, Blazor automatically re-renders the section to display the table. This conditional rendering is seamless and requires no custom JavaScript.
3. Simulating Latency and Data
The @code block simulates a real-world scenario where data might come from a slow database or an external API:
The OnInitializedAsync lifecycle method is where the component begins its work. By adding await Task.Delay(500), the code artificially pauses execution. This is what allows us to observe the Stream Rendering in action—we see the "Loading..." text for half a second before the table appears.
Summary
The Weather component teaches us three key lessons:
- Stream Rendering improves perceived performance by sending HTML chunks as they become ready.
- Razor Syntax allows for clean, logic-based rendering (checking for nulls).
- Lifecycle Methods like
OnInitializedAsyncare the standard place to initiate data loading operations.