Reputation: 1289
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
Upvotes: 8
Views: 13969
Reputation: 146
You can create a component and then cascade it down from app.razor or _host.razor.
Example inside component
<CascadingValue Value="this">
@ChildContent
</CascadingValue>
@code {
[Parameter]
public RenderFragment ChildContent { get; set; }
protected override void OnInitialized() => Expression.Empty()
}
Upvotes: 0
Reputation: 115
I think there is a misunderstanding/miscommunication between the OP and the replies thus far. Here's how it is:
Every Blazor page or component has its own OnInitializedAsync (and AfterRenderAsync etc) If you don't explicitly override them they inherit them from the base class.
These methods are called every time the page loads even after an F5 refresh.
But here's where I believe the misunderstanding lies: Take for example you have a site with two routes. the Index.razor page that's at the '/' route and MyPage.razor page that's at the '/mypage' route
If you navigate to /mypage and then press F5 the OnInitializedAsync method of the Index.razor file will not be hit. Only the one in MyPage.razor will be. If you have important values that are initialized in Index.razor that other pages depend on there will be a problem when you refresh one of those pages.
Upvotes: 1
Reputation: 69968
I had a similar problem and using the lifecycle event OnParametersSet{Async}
worked.
protected override void OnParametersSet()
{
}
Or
protected override async Task OnParametersSetAsync()
{
await ...
}
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://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-5.0
Upvotes: 1
Reputation: 63
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.
Upvotes: -4