'Socket io client keeps disconnecting and reconnecting in react-native app
I'm trying to get socket.io-client set up on my react-native app. I have an existing reactjs/nodejs project that uses socket.io and have not had any issues with it. On the server side I console.log every time a user connects or disconnects. I noticed that when I connect with my react native app the app keeps connecting and disconnecting to the server.
BspfKH-4A3-_Wn7nAAAT
BspfKH-4A3-_Wn7nAAAT
ywOdT3kUv9J05wTvAAAU
ywOdT3kUv9J05wTvAAAU
disconnected
disconnected
DNZG27GJmzpXJ1KwAAAV
DNZG27GJmzpXJ1KwAAAV
disconnected
uNZY5N_MIqggI4_BAAAW
uNZY5N_MIqggI4_BAAAW
P_SoiAwdgHjRNTcAAAAX
P_SoiAwdgHjRNTcAAAAX
disconnected
disconnected
00qadKZiqqMfe2MNAAAY
00qadKZiqqMfe2MNAAAY
DcDRnrNTEqhs7U9-AAAZ
In react-native I look to see if the user has a jwtToken (indicating they've performed a sign in) then set up the socket. Here's the code I'm using on the client side:
import io from "socket.io-client";
function App() {
useEffect(() => {
setTimeout(async() => {
if(await AsyncStorage.getItem('jwtToken') !== null){
console.log("connect")
var socket = io(getURL, {
transports: ['websocket'],
jsonp: false,
'forceNew': true
})
socket.on("new-message", message => console.log(message))
}
}, 1000);
}, []);
.....
I console.log when the user attempts to connect on the client so I know that part of the code only gets called once in the react-native side. Any ideas what might be going on here?
Solution 1:[1]
Alright, so for anyone who stumbled on this with similar issues - I actually had to uninstall my original socket.io-client package, then reinstall socket.io-client v2.1.1.
npm install [email protected]
Downgrading to v2.1.1 worked for me. Hopes this helps someone
Solution 2:[2]
I suggest to avoid using setTimout for socket connection, because with your code you are going to connect every second with forceNew option.
Try to do some refactore like this:
function App() {
const [jwtToken, setJwtToken] = useState(null);
useEffect(() => {
if(jwtToken){
console.log("connect")
var socket = io(getURL, {
transports: ['websocket'],
jsonp: false,
'forceNew': true
})
socket.on("new-message", message => console.log(message))
}
}, [jwtToken]);
and use setJwtToken to set the token. Even better it will be using an AuthenticationContext with React.createContext and useContext in your App function. In this way you can set your token easily in other components.
Solution 3:[3]
For me it's because my server has v2.03 and my client has ^4.5.0 after i'm upgrade my server to ^4.5.0 it works, but u need to change few of your codes, read the docs how
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Djaenike |
Solution 2 | Francesco Clementi |
Solution 3 | qahtan said |