0

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.

VasilyWRS
  • 21
  • 4
  • @HenkHolterman It has that in the Category Service. Are you suggesting I wrap the foreach in an if statement, then? – VasilyWRS Sep 06 '22 at 16:23

1 Answers1

1

what happens if response comes back as null here? var response = await _httpClient.GetFromJsonAsync<ServiceResponse<List<Category>>>("api/Category");

With how your logic is set up, you might need to add an empty list of categories in that case. Something like:

    if (response != null && response.Data != null)
        {
            Categories = response.Data;
        }
    else{
       Categories = new List<Categories>();
     }
Michael G
  • 535
  • 4
  • 12
  • What do you mean Henk Holterman? the call with "await" will hang until response is back and then you can act on that response. This happens all over the place. – Michael G Sep 07 '22 at 18:23