Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I disconnect from signalR when leaving a screen in react-native

In my app I have a few screens that use signalR like that. That function is called useEffect function and it works:

const setupSignalR = () =>
{
    SecureStore.getItemAsync("token").then(tk => {
            let connection = new HubConnectionBuilder()
            .withUrl("URL", {
            accessTokenFactory: () => tk
            })
            .build();

            connection.on("Update", function (message) {
             //DOSTUFF
            });

            connection.start()
            .then(() => console.log("connection started"))
            .catch(err => console.log("connecting hub failed err is : ", err));
    });
}

The problem is that if I leave the screen the connection stays open, and when I return to the screen I open another connection which means I now have 2 connections open at the same time. I know that signalR has a stop function that I can call, so I tried to use the navigation listeners like that, but they aren't called:

useEffect(() => 
{
    Load();
    setupSignalR();
    const unsubscribe = navigation.addListener('focus', () => {
        
      });
    const sub = navigation.addListener('blur', () => {
        console.log("============");
    });
}, [navigation]);

I generally leave a screen by pressing the back-button or by using navigation.navigate();

like image 929
user9210692 Avatar asked Sep 12 '25 23:09

user9210692


1 Answers

return () => {
    connection.stop();
}

Works.

like image 83
user9210692 Avatar answered Sep 14 '25 19:09

user9210692