Blazor and Browser page refresh

Viewed 3985

I have a Blazor WASM project that has properties that are initially setup in the OnInitializedAsync() method. All works fine, but if I hit the browser refresh button I get 'Object not set' error because all properties are reset and OnInitializedAsync() doesn't seem to run when you hit the browser refresh button. How does one re-initialized properties in this case? Is there a method that I should be using instead of OnInitializedAsync()?

Thanks

2 Answers

I had a similar problem and using the lifecycle event OnParametersSet{Async} worked.

protected override void OnParametersSet()
{
}

Or

protected override async Task OnParametersSetAsync()
{
    await ...
}

https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-5.0#after-parameters-are-set-onparameterssetasync

For some reason break points where not being hit when using the refresh button but I could "trick" the system by using NavigationManager.NavigateTo("/mypath/" + id); instead of refreshing via browser and I could then debug everything that happened.

Useful link for routing:

https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-5.0

The OnInitializedAsync() lifecycle function gets called every time the browser page is refreshed or a component is going to be rendered for the first time.

Related