'How to close connection when page closed and reloaded? (reactjs)

I have a problem with my asp.net core and reactjs app. I want to fire OnDisconnected method in backend side but I dont know how and when I can call this method?

This is my react code :

useEffect(() => {
    const newConnection = new HubConnectionBuilder()
      .withUrl('https://localhost:5032/hub/notif',
        {
          accessTokenFactory: () =>Token
        })
      .withAutomaticReconnect()
      .build();

    setConnection(newConnection);
    console.log(newConnection);
  }, []);

  useEffect(async () => {
    if (connection) {
      connection.start()
        .then(result => {
          console.log('Connected!');

          connection.on('RecieveNotification', message => {
            console.log(message);
          });
        })
        .catch(e => console.log('Connection failed: ', e));
    }
  }, [connection]);



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source