Razzupaltuff
Razzupaltuff

Reputation: 2301

Blazor Wasm notifiy parent component of state change

What code is needed to enable a Blazor child component to notify its parent component of state changes? I tried the following, which didn't work:

Helper class

    public class NotificationHandler
    {
        public event Action? Dispatcher;

        public void Notify() => Dispatcher?.Invoke();

        public void Attach(Action dispatcher) => Dispatcher += dispatcher;
        public void Release(Action dispatcher) => Dispatcher -= dispatcher;
    }

Parent Component

    @code
    {
        ChildComponent childComponent;
        StateNotifier stateNotifier;

        protected override Task OnInitializedAsync()
        {
            stateNotifier.Attach(StateHasChanged);
            return base.OnInitializedAsync();
        }
        
        // Overloading StateHasChanged() - does it work this way?
        protected new void StateHasChanged() // never gets called
        {
            DoSomething(); 
            base.StateHasChanged();
        }
    }

    <div>
        <ChildComponent StateNotifier="stateNotifier" />
    </div>

Child Component

    @code
    {
        [Parameter]
        public StateNotifier stateNotifier { get; set; }

        async void OnSomeUserAction()
        {
            stateNotifier.Notify();
        }
    }

Upvotes: 0

Views: 583

Answers (1)

Neil W
Neil W

Reputation: 9112

What code is needed to enable a Blazor child component to notify its parent component of state changes?

Simplest way is to use an EventCallback.

Child Component

<button @onclick=NotifyParent>Notify</button>

@code {
    [Parameter] public EventCallback OnSomethingHappened { get; set; }

    async Task NotifyParent()
    {
        await OnSomethingHappened.InvokeAsync();
    }
}

Parent Component

<ChildComponent OnSomethingHappened=@HandleSomethingHapppened />

@code {
    async Task HandleSomethingHappened()
    {
        await DoSomethingElse();
     
        // StateHasChanged() not needed when handling an event
        // The Blazor engine will automatically
        // run an Html diff after handling a component
        // event.

        // StateHasChanged();
    }
}

Upvotes: 2

Related Questions