SignalR instant notification doesn’t work at client page but after one refresh, it works fine

I have used signalR in my project to provide instant notification for the clients. When I send a message to a client, there is no update in the notification. But if I refresh the client page, the notification is updated and no further refresh is necessary. I checked the console in client page. There was an error:

Error: Cannot start a HubConnection that is not in the 'Disconnected' state.
    at L.j (signalr.js:1)
    at L.start (signalr.js:1)
    at pmPage:513

and after that, the following message has been written in the console:

[2022-01-08T07:37:35.208Z] Information: WebSocket connected to wss://localhost:7166/Home/Messages?id=hPCczwx4iIzIUdirBjH9ig.

Javascript code that I use is as follows (message.js):

    var connection = new signalR.HubConnectionBuilder().withUrl("/Home/Messages").withAutomaticReconnect().build();
connection.start();
if (document.getElementById("sendBtn") != null) {
    document.getElementById("sendBtn").addEventListener("click", function () {
        var costCenter = $("#cost-center").val();
        connection.invoke("SendMessage", costCenter).catch(function (err) {
            return console.error(err);
        });
    });
}

The code for Hub is:

public async Task SendMessage(string costCenter)
    {
        var HttpContext = _httpContext.HttpContext;
        string userId = _userRepository.GetUserIdByCostCenter(costCenter).ToString();
        string sender = HttpContext.Session.GetString("department");
        await Clients.User(userId).SendAsync("ReceiveMessage", sender);
    }

Javascript code for the client page:

<script>
connection.on("ReceiveMessage", function (param) {
    var currentMessageNum = parseInt($('#badge-count').text());
    var messageBadge = @Model.MessagesList.Where(x => x.receiverUserId == userId).Count();
    if($('#badge-count').length){
        $('#badge-count').text(currentMessageNum + 1);
        $('.main-msg-list').prepend('<li><a class="dropdown-item message-item" asp-controller="Messages" asp-action="Index" id="msg-'+ currentMessageNum + 1 +'">New message from '+ param +'</a></li>');
    }else{
        $('#badge-count').text('1');
    }
});
connection.start().catch(function (err) {
return console.log(err);
});

How can I fix this problem?