aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Parent losing track of children components

Open AlexStory opened this issue 8 years ago • 2 comments

Title

Parent components can have inconsistent updates based on their child components status.

Functional Impact

Reduces ability to break pages into components, affecting modularization, and code reuse.

Minimal repro steps

Follow the tutorial Then move the TodoItems in the foreach into a separate template that takes a TodoItem as a parameter.

Expected result

The parent component changes the number of items remaining when one is marked complete.

Actual result

The parent page component will no longer update the unfinished task count when a child element is marked complete. But it will update to the correct amount whenever a new child is added.

AlexStory avatar May 16 '18 12:05 AlexStory

namespace BlazorApp.Models {
    public class TodoItem {
        public string Title {get;set;}
        public bool IsDone {get;set;}
    }
}
@page "/todo"

<h1>Todo (@todos.Where(todo => !todo.IsDone).Count())</h1>

<ul class="list-group">
    @foreach (var todo in todos) {
        <TodoItem todo="@todo" />
    }
</ul>

<form>
    <input placeholder="Something todo" bind="newTodo" />
    <button onclick="@AddTodo" class="btn btn-primary">Add todo</button>
</form>


@functions {
    List<TodoItem> todos = new List<TodoItem>();
    string newTodo;

    void AddTodo(){
        if(!String.IsNullOrWhiteSpace(newTodo)){
            todos.Add(new TodoItem {Title = newTodo});
            newTodo = "";
        }
    }
}
@using BlazorApp.Classes

<li class="list-group-item form-inline">
    <input class-"form-control" type="checkbox" bind="todo.IsDone" />
    
    @if (todo.IsDone) {
        <del>@todo.Title</del>
    } else {
        @todo.Title
    }

</li>

@functions {
    [Parameter]
    Models.TodoItem todo {get;set;}
}

AlexStory avatar May 16 '18 12:05 AlexStory

Parent has no way of knowing when something changes in the child, you need to raise an event in the child and handle it in the parent, call StateHasChanged to re-render the parent.

dlr1 avatar May 16 '18 12:05 dlr1