Guy Z
Guy Z

Reputation: 693

View not updating after using js.InvokeAsync in Blazor

This code doesn't seem to remove the movie from the UI. The model does change. Only if I explicitly call StateHasChanged() will the UI change too.

Code:

@code{
    string name = "Guy";
    public bool display { get; set; } = false;
    [Parameter] public List<Movie> Movies { get; set; }

    private async void Delete(Movie movie)
    {
        bool confirm = await js.InvokeAsync<bool>("confirm", "Sure?");
        if (confirm == true)
        {

            Movies.Remove(movie);
            Console.WriteLine(Movies.Count);
            //StateHasChanged();
        }
    }

}

And UI is simple as that:

@inject IJSRuntime js
<h1>Hello, world!</h1>

Welcome ,@StringsHelpers.toUpper(name) , to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<div>
    <h3>Movie</h3>
    <input type="checkbox" @bind="display" />
    <GenericList List="Movies">
        <ElementTemplate>
            <IndMovie IsDisplayed="display" Movie="context" Delete="Delete"></IndMovie>
        </ElementTemplate>
    </GenericList>

    <div>
        @foreach (var item in Movies)
        {
            @item.Title
        }
    </div>

    <br />
</div>

Upvotes: 1

Views: 460

Answers (2)

Carlos Lopez Soto
Carlos Lopez Soto

Reputation: 16

try this:

  public async Task Delete(Movie movie)
    {
        bool confirm = await js.InvokeAsync<bool>("confirm", "Sure?");
        if (confirm == true)
        {

            Movies.Remove(movie);
            Console.WriteLine(Movies.Count);
            //StateHasChanged();
        }
    }

Other problem can be if the List of Movies not update de state in the parent.

If the code don´t make you try to put Delete method in the parent component and pass this like parameter

Upvotes: 0

Guy Z
Guy Z

Reputation: 693

Seems like the private async void Delete(Movie movie) should return Task instead

Upvotes: 1

Related Questions