0

I have a blazor app page, and when i go there by the link from another page, it works and i can see h1 header with correct value, but if i will click F5 or call reloadpage method, it throws NullReferenceException on line with h1 header, like item object is null. How can i avoid that behaviour?

...
@inject NavigationManager MyNavigationManager
@page "/items/{id}"

...

<h1>@_item.Name<h1>

...

[Parameter]
public string Id { get; set; }

private Item _item;

protected override async Task OnInitializedAsync()
{
    _item= await ItemsService.GetItem(Id);
}

private void ReloadPage(bool forceLoad = false)
{
    MyNavigationManager.NavigateTo($"/items/{Id}", forceLoad);
}

1 Answer 1

2

OnInitializedAsync is exactly what it sounds like, it's an asynchronous method. The data for Item may not be available when the razor component renders. You should check for nullability before trying to display it.

@if(_item is not null)
{
    <h1>@_item.Name<h1>
}

You may be able to do something like this as well:

<h1>@(_item.Name ?? "Not Available")</h1>

Read more here

Sign up to request clarification or add additional context in comments.

3 Comments

But there is an await inside of the OnInitializedAsync while assigning to _item.
@SiddharthSeth, read this, you're incorrect in your understanding of the Blazor page life cycle: learn.microsoft.com/en-us/aspnet/core/blazor/components/…
To clarify here, the moment your Task yields with a continuation, the internal component code calls StateHasChanged and the Renderer has processor time to run it. It's designed that way so you can show a "Loading" message if your async task is slow. It runs a second StateHasChanged at the end of the OnInitialized/OnParametersSet code block for the final component render.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.