Reputation: 79
I've been instructed to work on a new project where I'll be using MVVM in a Blazor wasm.
I've been following the videos by Carl Franklin, where you create an interface of a viewmodel and inject this directly into the view using @inject with no code behind, and for the most part this is working great.
But after developing a few pages I needed to automatically fetch data during the load of the page. In normal Blazor you would use one of the lifecycle methods for this (like OnInitializedAsync), but since we're not using any code-behind those methods are not available. In dotnet your ctor also can't be async so I can't do it here either, and the asynchronous initialization pattern also doesn't provide me with the correct result.
I've been looking around a bit and can't seem to find the proper way to do it, does anyone have experience with this issue or know the answer?
Below is some pseudo code to describe the usual setup (which worked until this use case)
Example of view:
@path "/";
@inject IIndexViewModel viewmodel;
<ul>
@foreach (var item in viewmodel.Items)
{
<li>@item.Name</li>
}
</ul>
Example of IViewModel
List<Item> Items;
Task FetchItems();
Example of ViewModel
private readonly IItemService _service;
public IndexViewModel(IItemService service)
{
_service = service;
Items = [];
}
public List<Item> Items {get; set;}
public async Task FetchItems()
{
Items = await _service.GetItemsAsync();
}
The issue is that the FetchItems call needs to happens automatically and not base on a user action, and this is causing the issues.
I'm also not allowed to use the code-behind, so fixes involving anything other than the viewmodel are out of the question as well.
EDIT: the issue is not the FetchItems method, because it works perfectly when attached to a button. Sadly this is no help, as the method should be called automatically without user input.
EDIT2: I've also tried to add a div with an @onload unto the html, but it seems the onload event isn't called by Blazor wasm.
Kind regards
Upvotes: 0
Views: 50