I have a single page on a Blazor App that I'm looking to have refresh the data every so often.
The timer works, I can set a breakpoint and see that the data is updating, but the InvokeAsync calls to notify that StateHasChanged appear to do nothing.
Every second I see the API call to the front end, I see that _horses contains the updated data afterwards.
@page "/"@using DerbyStonks.Blazor.Services.Derby.Entities@using System.Timers@inject IHttpClientFactory ClientFactory@inject NavigationManager NavigationManager<PageTitle>Home</PageTitle><br/><h1>Horses</h1>@if (_loading){<h3>Loading ...</h3>}else{<ul class="horse-list"> @foreach (Horse horse in _horses) {<li class="horse-list-item"><h2>#@horse.Number: @horse.Name</h2></li> }</ul>}@code{ Timer _timer; bool _loading = true; List<Horse> _horses = new List<Horse>(); protected override async Task OnInitializedAsync() { await LoadHorses(); StartHotReload(); } private void StartHotReload() { _timer = new Timer(1000); // 1 second interval _timer.Elapsed += async (sender, e) => await LoadHorsesAndUpdateUI(); _timer.AutoReset = true; _timer.Enabled = true; } private async Task LoadHorsesAndUpdateUI() { try { await LoadHorses(); await InvokeAsync(StateHasChanged); } catch (Exception ex) { // Handle exception (e.g., log, display error message) } } private async Task LoadHorses() { HttpClient client = ClientFactory.CreateClient(); client.BaseAddress = new Uri(NavigationManager.BaseUri); _loading = true; try { var horses = await client.GetFromJsonAsync<List<Horse>>("api/Horses"); if (horses != null) { _horses = horses; } else { _horses.Clear(); // Clear the list if no horses are returned } } finally { _loading = false; } } public void Dispose() { _timer?.Dispose(); }}I've been at this for a day or so, I've tried a number of unsuccessful permutations on this problem.
- If I call
StateHasChangeddirectly, it doesn't have access to the dispatcher. - If I make the timer non-static, it gets disposed almost immediately and does nothing
- I've consulted a number of sources trying to hunt this down
- I've consulted ChatGPT and permutated on solutions/changes offered by it.