question

osyris-3187 avatar image
0 Votes"
osyris-3187 asked JonGalloway3000 answered

Signalr connection problem

every time i try to invoke the signalr connection i get a error message:

Unhandled Rejection (Error): Cannot send data if the connection is not in the 'Connected' State.

while the first thing i do is starting the connection i even get a comformation
in the console log saying: "SignalR is now connected"

reactjs code:



    useEffect(() => {
          
         const Connection = new HubConnectionBuilder()
         .withUrl('https://localhost:44332/chatHub')
         .withAutomaticReconnect()
         .build();
         setNewConnection(Connection)
            
         Connection.start().then(result => { console.log("SignalR is now connected")});
            
 Connection.invoke("JoinGroup", "PrivateGroup");
  Connection.on("ReceiveMessage", (message) => {
         setTestName(message)})
         },[]); 

the back end:


     public async Task JoinGroup(string group)
         {
             await Groups.AddToGroupAsync(Context.ConnectionId, group);
         }
    
         public async Task SendMessageToGroup(string group, string message)
         {
             await Clients.Groups(group).SendAsync("ReceiveMessage", message);
         }


dotnet-aspnet-core-generaldotnet-aspnet-generaldotnet-aspnet-core-security
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JonGalloway3000 avatar image
1 Vote"
JonGalloway3000 answered

Connection.invoke immediately returns a JavaScript promise, so I think you need to chain then() calls for anything that requires the connection to be started and available.

While the code looks like it's invoking JoinGroup after the Connection has started, what actually happens is the Connection start method is called, a promise is returned while waiting for the connection to be established between client and server, and immediately after that the invoke method is called before the connection is fully started.

 Connection.start().then( result => { 
   console.log("SignalR is now connected")
 }).then( result => {
   Connection.invoke("JoinGroup", "PrivateGroup")
 });
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.