Blazor - Equivalent to Vue Watch for a Parameter

Viewed 1180

Coming from a VueJS background to Blazor, I can't find an equivalent to the Vue watcher in Blazor.

To elaborate, in Vue, one could watch for changes on a certain property, for example:

watch: {
   somethingId(newValue) {
      // Do something, this actually watches the somethingId for change and trigger this function
   }
}

I can't seem to find an equivalent to Blazor, I tried to achieve that using a custom property's getter/setter but this does not work in all cases (it is actually more similar to computed properties in vue and not a watch).

Is there a way to achieve this?

2 Answers

This functionality is not available in Blazor as per the team on the ASP.NET Github Repository.

I ended up implementing a state container (a similar concept to Vuex in VueJS) to store the common values that I'm looking to observe (instead of passing them as Parameters) and throwing events upon their changes. This is documented in ASP.NET Core Blazor state management.

Let's say we need to watch/observe the changes to somethingId, similar to the example above:

  1. Create a SomethingStateContainer class with the following:
public class SomethingStateContainer
{
    public event Action<int> OnSomethingIdChanged; // Or any type, here SomethingId is an int

    private int _somethingId = 0;
    public int SomethingId {
        get => _somethingId;
        set {
            _somethingId = value;
            OnSomethingIdChanged?.Invoke(value);
        }
    }
}

This service is then added as a singleton within the Program.cs (if using Blazor WebAssembly):

builder.Services.AddSingleton<SomethingStateContainer>();
  1. Each component looking to listen on changes done over this variable can do so as follows:
  • Inject the SomethingStateContainer within the Blazor component:
@inject SomethingStateContainer SomethingStateContainer
  • Add an event listener (and dispose it when done):
protected override async Task OnInitializedAsync()
{
    SomethingStateContainer.OnSomethingIdChanged += YourCallbackFunction;
}

public void Dispose()
{
    SomethingStateContainer.OnSomethingIdChanged -= YourCallbackFunction;
}

Where the YourCallbackFunction is the function that you wish to execute (In this case it takes an int as an input):

private void YourCallbackFunction(int id)
{
    // Do something
}

Use OnParametersSet(),this event happen after OnInitialzed.

enter image description here

@code{
  [Parameter] public int UserId{get;set;}
  private int _userId;

  protected overrid void OnParametersSet(){
    if(_userId!=UserId){
      _userId=UserId;
      //do something
    }
  }
}

Related