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();