0
votes

In Blazor, on the client side, I have a page that has a list of Items, and a custom table component that takes that list of items as parameter. However, when I update the item list on the page (delete item), the change is not reflected in the table (child component). How do I trigger updates on child component when the underlying data collection has changed in the parent component?

Edit: This is my table component (child):

@typeparam TableItem

<CascadingValue Value="this">
    <Table>
        <TableHeader>
            <TableRow>
                @CustomTableHeader
            </TableRow>
        </TableHeader>
        <TableBody>
            @foreach (var item in Items)
            {
                <TableRow>
                    @CustomTableRow(item)
                </TableRow>
            }
        </TableBody>
    </Table>
</CascadingValue>

@functions {

    [Parameter]
    public List<TableItem> Items { get; set; }  
    
    //different methods
    
    private void Refresh()
    {
        InvokeAsync(() =>
        {

            StateHasChanged();
        });
    }
}

And this is how I use it from the page (parent component):

<CustomTable Items="_myItems">
    <CustomTableHeader>
        <CustomTableCell TableItem="MyType" Name="ItemName1" >Item Name1</CustomTableCell>
        <CustomTableCell TableItem="MyType" Name="ItemName2" >Item Name2</CustomTableCell>
    </CustomTableHeader>
    <CustomTableRow>
        <TableRowCell>@(context.ItemName1)</TableRowCell>
        <TableRowCell>@(context.ItemName2)</TableRowCell>
    </CustomTableRow>
</CustomTable>

@code
{
    private string List<MyType> _myItems = new();
    
    private void DeleteItem(string identifier)
    {
        //deleteItem code
    }
}
1
Can you show how you are passing data to the child component? - Mayur Ekbote
@MayurEkbote I updated my question with the details - user2399378

1 Answers

0
votes

You need to use events. You need to create a shared service. Subscribe to the service's Update event in the parent and Invoke() from your child component. In the parent method call StateHasChanged();

public interface IMyService
{
    event Action Update;
    void CallUpdate();
 }

public class MyService: IMyService
{
    public event Action Update;
    public void CallUpdate()
    {
         Update?.Invoke();
    }
}


//child component
MyService.CallRequestRefresh();


//parent component
MyService.CallUpdate += UpdateMe;

private void UpdateMe()
{
    StateHasChanged();
}