dotnet-presentations / blazor-workshop

Blazor workshop
https://aka.ms/blazorworkshop
MIT License
3.47k stars 1.54k forks source link

ConfigurePizzaDialog not showing unless I call StateHasChanged #338

Closed shawndewet closed 2 years ago

shawndewet commented 2 years ago

I got stuck for a lo-o-o-o-ng time on this step: https://github.com/dotnet-presentations/blazor-workshop/blob/main/docs/02-customize-a-pizza.md, at the point of the first Run of the solution in that step, here: image

The behaviour I was experiencing was that the ConfigurePizzaDialog just was not showing after I click on a Special. I started going crazy with Console.WriteLine statements to understand what is happening, like so:

void ShowConfigurePizzaDialog(PizzaSpecial special)
    {
        Console.WriteLine($"showing {special.Name} now");
        configuringPizza = new Pizza()
            {
                Special = special,
                SpecialId = special.Id,
                Size = Pizza.DefaultSize,
                Toppings = new List<PizzaTopping>()
            };
        Console.WriteLine($"configuringPizza {configuringPizza.SpecialId} done");

        showingConfigureDialog = true;
        Console.WriteLine($"showingConfigureDialog: {showingConfigureDialog}");
    }

All the above Console.WriteLine statements would display, but the UI just did not show the ConfigurePizzaDialog.

In the markup, I also added this to see what's happening:


@if (showingConfigureDialog)
{
    <ConfigurePizzaDialog Pizza="configuringPizza" />
}
<div>
    <p>Always:</p>
    <p>@(configuringPizza == null ? "No pizza selected" : configuringPizza.Special.Name)</p>
</div>

The bottom div displayed in the UI, but it always just displayed "No pizza selected". Correspondingly, ConfigurePizzaDialog never shows, because showingConfigureDialog stays false.

Eventually I added StateHasChanged() as the last line of my ShowConfigurePizza() method, and only then did the display get updated when I click on a pizza special.

Why is this? What am I missing? I'll leave the StateHasChanged() call there for now, but I don't understand why it is needed when it is not in this tutorial's code? I must be missing something?

shawndewet commented 2 years ago

I found the problem! In the

  • for each special, I was using onclick= instead of @onclick=!!!