Quinton
Quinton

Reputation: 141

Blazor not updating from JS

I followed this tutorial which works perfectly https://dotnet.microsoft.com/learn/aspnet/blazor-tutorial/try

I ran into a issue though, I need to increment the counter from JavaScript, from an event from my service worker. If I use static interop the value in counter updates, but the UI doesn't display the update. I tried to change the interop to an instance method instead but cannot get that to work.

HTML

        const broadcast = new BroadcastChannel('count-channel');

        // Listen to the response
        broadcast.onmessage = (event) => {
            DotNet.invokeMethod('MyApp.Client', 'IncrementCount', 'no param');

            console.log("done");
        };

Razor

    @page "/counter"
    
    <h1>Counter</h1>
    
    <p>Current count: @currentCount</p>
    
    <button class="btn btn-primary" @onclick="IncrementMe">Click me</button>
    
    @code 
{
    static int currentCount = 0;
    
    public void IncrementMe()
    {
        currentCount++;
    }

    [JSInvokable]
    public static void IncrementCount(string ignore)
    {
        currentCount++;
    }

}

Upvotes: 1

Views: 1869

Answers (2)

The Backer
The Backer

Reputation: 718

We can pass instance to Javascript :

 private int currentCount = 0;

    private async Task IncrementCount()
    {
        await JSRuntime.InvokeVoidAsync("incrementCountFromJs", DotNetObjectReference.Create(this), nameof(JsMethod));
    }

    [JSInvokable]
    public void JsMethod()
    {
        currentCount++;
        StateHasChanged();
    }
}

app.js:

function incrementCountFromJs(instance, callback) {
    instance.invokeMethodAsync(callback);
}

Upvotes: 4

Nicola Biada
Nicola Biada

Reputation: 2800

Add a StateHasChanged after increment.

Look at Microsoft official documentation:
https://learn.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-5.0#state-changes-statehaschanged-1

Upvotes: 0

Related Questions