Edit: I am specifically wanting it to not send a message to the front end. With breakpoints you can see that the response in GetCategoriesAsync() starts as null while it awaits the database response.
I am building an E-Commerce website to display my wife's crochet projects on using Blazor in Dotnet 6. Now, the website is functioning just fine, but it pops up a message that an unhandled error has occurred every time the Nav bar is loaded. The error is as follows:
Crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Object reference not set to an instance of an object.System.NullReferenceException: Object reference not set to an instance of an object.
at MermaidCraftsFE.Client.Shared.NavMenu.BuildRenderTree(RenderTreeBuilder __builder) in C:\Users\scull\source\repos\MermaidCraftsFE\MermaidCraftsFE\Client\Shared\NavMenu.razor:line 19
at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0(RenderTreeBuilder builder)
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
The code indicated by the error is here:
@foreach (var category in categoryService.Categories)
{
<div class="nav-item px-3">
<NavLink class="nav-link" href="@category.Url">
@category.Name
</NavLink>
</div>
}
And the category service code which is necessary is here:
public async Task GetCategoriesAsync()
{
var response = await _httpClient.GetFromJsonAsync<ServiceResponse<List<Category>>>("api/Category");
if (response != null && response.Data != null)
{
Categories = response.Data;
}
}
What am I missing that is causing this error? Demonstration is in a week from today and I would like for this error box to not pop up when the function is behaving as expected. I have tried changing the var
in
var category in categoryService.Categories
to Category
, but the error pops up all the same.