Connecting to a SingalR Group

1 minute read

At work I have been using SingalR core for a project that needs to have real time updates to records be shown without any user interaction (i.e. page refresh). But I want these changes to only be consumed by group of users. Reading thru the SignalR documentation it looks like you can use groups to do this. The documentation seemed straight forward, but when it came time to actually implement this, I was having a hard time understanding how to join a group.

It turns out that I didn’t read the documentation thoroughly enough. When you connect to a SignalR hub using the Javascript client, you are returned a Promise object. You can then use this Promise object to connet to the group. Below is the code that I used to successfully connect to the group:

var connection = new signalR.HubConnectionBuilder()
                            .withUrl("../serviceline-messages")
                            .build();
connection.start()
          .then(function() {
              connection.invoke("JoinGroup", serviceLineID)
                  .catch(function(error) {
                      return console.error("JoinGroup Error: " + error)
                  });
          })
          .catch(function(error) {
              console.error(error);
          });

So the key to this issue is to make sure that when going thru documentation that you understand what your reading. It’s easy to skim thru documentation and pretend that you know what is being discussed but when you try to implement something and you cannot, then this is a sign that you really didn’t understand the documentation/concepts that you just read. Instead of going forward and try to understand how to solve the problem step back and re-read the documentation (a few times if needed) to make sure you are really following what’s recommended.

Leave a comment