mrpmorris / Fluxor

Fluxor is a zero boilerplate Flux/Redux library for Microsoft .NET and Blazor.
MIT License
1.27k stars 147 forks source link

[Docs] Component not derived from `FluxorComponent` #349

Closed lonix1 closed 1 year ago

lonix1 commented 1 year ago

I've a component derived from a class other than FluxorComponent.The docs state:

Also, add the following line to the top of the razor file

@inherits Fluxor.Blazor.Web.Components.FluxorComponent

Note: This is required to ensure the component re-renders whenever its state changes. If you are unable to descend from this component, you can instead subcribe to the StateChanged event and execute InvokeAsync(StateHasChanged). If you do use the event, remember to implement IDisposable and unsubscribe from the event too, otherwise your app will leak memory.

Does someone have an example of what that looks like?

mrpmorris commented 1 year ago

Any time you inject IState<Whatever> it has an event on it that you can subscribe to. Make sure you unsubscribe when your component is disposed.

lonix1 commented 1 year ago

Ok I didn't know where that event was defined, thanks for that!

lonix1 commented 1 year ago

Just to be sure I understood, this is what I have:

@inherits MudComponentBase          @* not FluxorComponent *@
@implements IDisposable

...markup...

@code {
  [Inject] private IState<MyState> State { get; set; } = default!;

  protected override void OnInitialized() {
    base.OnInitialized();
    State.StateChanged += HandleStateChanged;
  }

  public void Dispose() => _state.StateChanged -= HandleStateChanged;

  private void HandleStateChanged(object? sender, EventArgs e) => InvokeAsync(StateHasChanged);
}

Is that what you referred to?

mrpmorris commented 1 year ago

That is spot on!

You could also use this to subscribe to all state properties in one go and dispose the IDisposable it returns when finished.

https://github.com/mrpmorris/Fluxor/blob/master/Source/Lib/Fluxor/StateSubscriber.cs#L30

neozhu commented 5 months ago

That is spot on!

You could also use this to subscribe to all state properties in one go and dispose the IDisposable it returns when finished.

https://github.com/mrpmorris/Fluxor/blob/master/Source/Lib/Fluxor/StateSubscriber.cs#L30

Can you give me an example of how to correctly subscribe to an IState state value without inheriting from FluxorComponent?