React .NET - Display all active connections with SignalR

Viewed 53

I am working with a application using React as frontend and .net as backend.

Right now I am trying to add the connections as a number to show users how many people there is active on the application right now, I want the number to update in real-time, with this I am using SignalR.

What happends is when 1 user is active, instead of showing 1, it shows 3. When 2 users are active, it shows 6-7 and keeps going like this.

Let me show you some code

OnConnectionCountHub.cs

public class OnConnectionHub : Hub
{
    public static int ConnectionCount { get; set; }

    public override Task OnConnectedAsync()
    {
        ConnectionCount++;
        Clients.All.SendAsync("updateConnectionCount", ConnectionCount).GetAwaiter().GetResult();
        return base.OnConnectedAsync();
    }

    public override Task OnDisconnectedAsync(Exception? exception)
    {
        ConnectionCount--;
        Clients.All.SendAsync("updateConnectionCount", ConnectionCount).GetAwaiter().GetResult();
        return base.OnDisconnectedAsync(exception);
    }
}

Fairly simple.

ConnectionCount.tsx

export const ConnectionCount = () => {
    const [connectionCount, setConnectionCount] = useState(0)
    // create connection
    useEffect(() => {
        const connection = new HubConnectionBuilder()
        .withUrl(urlOnConnectionHub)
        .build()

    // connect to method that hub invokes
    connection.on("updateConnectionCount", (onConnection) => {
        setConnectionCount(onConnection)
        }
    )

    // start connection
    connection.start().then(() => {
        console.log("Connection started")
    });
    }, [])
    

    return(
        <section>
            <p>Active users: {connectionCount}</p>
        </section>
    )
}

My guess would be, because this is a component, it gets double the connections where ever I am using the component, instead of one connection all over.

Any idea on how to fix this? UseContext maybe?

1 Answers

try this on client side :

export  const ConnectionCount = () => {
const [connectionCount, setConnectionCount] = useState(0)

const connection = new HubConnectionBuilder()
.withUrl(urlOnConnectionHub)
.build()

connection.on("updateConnectionCount", (onConnection) => {
    setConnectionCount(onConnection)
 });

useEffect(() => {        
      if (connection.state === HubConnectionState.Disconnected){
            connection.start().then(() => {
                console.log("Connection started")
            });
        }                     
    }, []);

     return(
         <section>
            <p>Active users: {connectionCount}</p>
         </section>
  )
}
Related