ComponentReferenceCapture update in blazor

Viewed 773

In a blazor sample, I am using a RenderFragment to update the elements dynamically and also captured the component reference for each updates. While capturing elements initially, it captures the component reference properly. When I update a component, it retains the older componentReference. Component reference did not update properly.

Index.razor

@page "/"

<button @onclick="AddContent">1st Update</button>
<button @onclick="AddSecondContent">2nd Update</button>
<button @onclick="CheckContent">Check Update</button>
@DataContent

@code {
    RenderFragment DataContent { get; set; }
    List<Counter> CounterReference = new List<Counter>();
    void AddContent()
    {
        DataContent = (Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) =>
        {
            int seq = 0;
            for(int i = 0; i < 3; i++)
            {
                builder.OpenComponent<Counter>(seq++);
                builder.AddComponentReferenceCapture(seq++, ins => { CounterReference.Add((Counter)ins); });
                builder.CloseComponent();
            }

        };
        InvokeAsync(StateHasChanged);
    }

    void AddSecondContent()
    {
        CounterReference.Clear();
        DataContent = (Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) =>
        {
            int seq = 0;
            for (int i = 0; i < 2; i++)
            {
                builder.OpenComponent<Counter>(seq++);
                builder.AddComponentReferenceCapture(seq++, ins => { CounterReference.Add((Counter)ins); });
                builder.CloseComponent();
            }

        };
        InvokeAsync(StateHasChanged);
    }

    void CheckContent()
    {
        Console.WriteLine();
    }
}

counter.razor

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    public void IncrementCount()
    {
        currentCount++;
    }
}

In the above sample, I have updated the DataContent initially, I am getting Count of CounterReference as 3. After this, I cleared a CounterReference and I updated the DataContent. In the second case, I am rendering 2 Counter component which rendered in the DOM properly. But I am getting Count of CounterReference as 0. In the second update, If I did not clear the CounterReference, I am getting its value as 3. Such that it retains its previous value. I am expecting this value to be 2.

What I am doing wrong with this?

0 Answers
Related