Execute a method each time StateHasChanged is called

Viewed 218

Suppose I have this blazor component (I'm using wasm):

<p>@name</p>

@code{
  private int id;
  public void SetId(int id) // will be called by another component that has a reference to this component
  {
    this.id = id;
    StateHasChanged();
  }

  private string name;
  private async Task UpdateName()
  {
    // httpService is injected
    this.name = await httpService.Get<string>($"api/getname?id={this.id}");
  }
}

How do I manage to call the UpdateName method each time SetId (hence StateHasChanged) is called ?

I tried calling it inside lifecycle methods SetParametersAsync and OnParametersSetAsync. But I think these methods are not being invoked each time StateHasChanged is called. Probably because the component has no parameters.

1 Answers

will be called by another component that has a reference to this component

Then the preferred, clean approach is to not use compRef.SetId(id) but to pass the Id as a parameter:

 <MyComponent Id="id" />

Give your component a [Parameter] public int Id {get; set; } and call UpdateName() from OnParameterSetAsync()


Additional, a simple way with SetId().
You should normally avoid async void but in this case it is appropriate.

private int id;
public async void SetId(int id) // will be called by another component 
{
  this.id = id;

  // await so it is complete before the next line.
  await Updatename();            

  // when you know you always call it from the UI
  StateHasChanged();  

  //// or Invoke to avoid Cross-Threading issues. The await is optional.
  //await InvokeAsync(StateHasChanged);
}

The responsibility for calling StateHasChanged() clearly belongs to SetId().

Related