.netasp.net-coresignalr

SignalR hub connection StateChanged not working client


Working with .net Core and have setup everything using this tutorial: https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-3.1&tabs=visual-studio.

I wanted to be able to use lifetime events based on this tutorial: https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client

However I get:

connection.stateChanged or connection.disconnected is not a function

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.start().then(function () {
}).catch(function (err) {
    return console.error(err.toString());
});

connection.stateChanged(function () {
    console.log('in');
});

I would like to detect "disconnected" even on the client.


Solution

  • From the MS Doc on HubConnectionState , there are only 2 states:

    Those states are exposed through a state property in the connection but there are no states for anything else.

    From the what anurse said in this github issue , thestart Promise lets you know when the connection starts and the closed event lets you know it's stopped. They don't have automatic reconnects, so those are the only state transitions.

    So you could use the following method as Dennis1679 said above

    connection.onclose(function(){
        console.log('connecition closed');
    });