I’m having difficult with getting my UI to automatically update, I’ve bound LifetimeService.Items to the table yet its not updating when I call InvokeAsync(StateHasChanged)
I’ve tried everything I can think of such as IDisposible on LifetimeService, changing from List to OberservableCollection etc as well as cleaning and rebuilding my project.
I’ve double checked the Items list is populating correctly and it is
Any help would be greatly appreciated. Thankyou
Here is my table
table class="table">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Price</th>
<th>Link</th>
<th>ItemSlot</th>
</tr>
</thead>
<tbody>
@foreach (var item in LifetimeService.Items)
{
<tr>
<td><img src="@item.Image" alt="Image" width="100" height="100" /></td>
<td>@item.Name</td>
<td>@item.Price</td>
<td><a href="@item.Link">Link</a></td>
</tr>
}
</tbody>
</table>
I have a class LifetimeService containg Items List
public class LifetimeService
{
public int ScanAmounts = 0;
public List<Item> Items { get; set; } = new List<Item>();
public bool AddItem(Item item)
{
if (Items.Any(x => x.Name == item.Name && x.Price == item.Price && x.Image == item.Image && x.Link == item.Link))
{
return false;
}
if (ScanAmounts == 0)
{
Items.Add(item);
return true;
}
else
{
Items.Insert(0, item);
return true;
}
}
}
I have my method running on a timer which grabs data then runs
await InvokeAsync(StateHasChanged);
protected override async Task OnParametersSetAsync()
{
await base.OnParametersSetAsync();
if (LifetimeService.Items.Count > 0)
{
return;
}
StartTimer();
await ScrapeData();
}
private void StartTimer()
{
_timer = new Timer(async _ =>
{
await InvokeAsync(ScrapeData);
}, null, TimeSpan.Zero, TimeSpan.FromMinutes(1));
}
private async Task ScrapeData()
{
{
{
...
var added = LifetimeService.AddItem(new Item { Name = name, Price = price, Image = img, Link = link });
if (added)
{
addedAnythingToList = true;
Debug.WriteLine("Title: " + title);
Debug.WriteLine("Price: " + price);
Debug.WriteLine("Name: " + name);
Debug.WriteLine("Image: " + img);
}
}
if (addedAnythingToList)
{
Debug.WriteLine("Invoking state has changed");
await InvokeAsync(StateHasChanged);
Debug.WriteLine("Finished Invoking");
}
// Close the browser
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
Debug.WriteLine("Inner: " + ex.InnerException);
}
finally
{
// Ensure the driver quits even if an exception occurs
driver.Dispose();
driver.Quit();
Process[] processes = Process.GetProcessesByName("chromedriver");
foreach (Process process in processes)
{
process.Kill();
}
stopwatch.Stop();
Debug.WriteLine("Time taken: " + stopwatch.Elapsed);
await InvokeAsync(StateHasChanged);
LifetimeService.ScanAmounts++;
}
...