Is the template project which gets data for the weather page flawed in the sense that data is retrieved in the OnInitializedAsync() method?
- In the real world, you likely want pre-rendering to occur
- You want some sort of "loading..." indicator while you obtain your data
- And assume getting the data is a "long running" process
The template project will get the data twice, if you refresh the weather page (or request it directly from the browser), rather than using the interactive (enhanced) navigation from another page.
It seems a much better way to handle this situation is to do something like the following (I am using a weatherService to get the WeatherForecast data):
protected override async Task OnAfterRenderAsync(bool firstRender){ if (firstRender) { forecasts = await weatherService.GetWeather(); StateHasChanged(); } await base.OnAfterRenderAsync(firstRender);}This seems to be the simplest way to guarantee that the app is not accessing the data twice.
Here's another alternative (and it is arguably better, according to some people)
[CascadingParameter]HttpContext? HttpContext { get; set; }protected override async Task OnInitializedAsync(){ if (HttpContext == null) // i.e. this is not a pre-render situation, and will be the final call to this method for this request { forecasts = await weatherService.GetWeather(); }}In any case, the example project should not be obtaining data twice.Am I missing something?