0

StateHasChanged method not re render the component once the collection removed. We are tried to Re render the component once the collection item is updated by using StateHasChanged but it executes the next statement. After completion of the all lines then only component re renders.

Main goal is : I want to detect the button deletion once its updated in the UI. So, if StateHasChanged method re render the component then UI will be updated.

Code block

@if (Collection.Count > 0)
{
 <div>
     
     @for (var i = 0; i< Collection.Count; i++) {
        <button @onclick=@(() => OnDeleteClick())>@Collection[i]</button>
     }
  </div>
}

@code{

private List<string> Collection = new List<string>();

public class DelArgs
{
    public string Text { get; set; }
}

    protected override void OnInitialized()
    {
        Collection.Add("Chai");
        Collection.Add("Chang");
        Collection.Add("Ikura");
        Collection.Add("Anna");
    }

    private async Task OnDeleteClick()
    {
        Collection.RemoveAt(0);
        StateHasChanged();
        Console.WriteLine("Item Deleted!!");
    }
}`
  • Unclear. StateHasChanged() is almost the last line in OnDeleteClick, so what does "After completion of the all lines then only ..." mean exactly? Is this the exact code? – H H Oct 27 '21 at 11:15
  • Consider providing a [mre]. The answers will only be as good as the question. – H H Oct 27 '21 at 11:17
  • `private async void ` - this might be the problem - don't do this. It should always be `private async Task`. This returns a Task that the runtime can wait for. Otherwise it's not really going to work – Quango Oct 27 '21 at 12:16
  • @Quango - because of `async void` the StatehasChanged() is required. Besides that, `void` , `async void` and `async Task` should all work here. The real problem was not posted. – H H Oct 27 '21 at 12:28
  • `async void` [should still not be used](https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming). You're not returning the task so it *might* run it might not. It's bad practice to use the wrong approach – Quango Oct 27 '21 at 12:30
  • Changed to *async Task* but having same issue. – Muthukrishnan Kandasamy Oct 27 '21 at 12:38
  • Told you not to call StateHasChanged, but you still insist on calling it. Why ? Your code, I mean the original code is working. I believe that I understand you now: DO YOU WANT THE COMPONENT TO RE-RENDER ONCE the StateHasChanged method has been called, before Console.WriteLine("Item Deleted!!"); is executed ? – enet Oct 27 '21 at 12:47

0 Answers0