Reputation: 41
I'm developing a chat app where two users can talk to one another and I'm doing this with flask-socketio and React.
I've been struggling with trying to figure out this issue I'm getting with socket.io. Here's the error connection I keep getting once in a while on the browser console:
WebSocket connection to 'ws://127.0.0.1:5000/socket.io/?EIO=4&transport=websocket&sid=s8DKBembmWoxgGAsAAqX' failed: Insufficient resources
I'm having a difficult time trying to figure out what's causing this error. The way I solved this was to refresh the page and the connection is then re-established. I want to find a solution to this where I don't keep being disconnected from the socket and getting the same error message. Any idea on how to do this?
Upvotes: 4
Views: 20884
Reputation: 1549
One common issue with sockets and react is how often you instantiate a WebSocket.
Here's an example of how it shouldn't be set up in a react component. Every time the component rerenders, a new socket will be set up, which will cause an Insufficient resources
error.
import React, {useState} from 'react'
import { io } from "socket.io-client";
export default function MockSocket() {
const [message, setMessage] = useState("");
const socket = io();
socket.connect();
socket.on("recieve_message", setMessage);
return (
<div>
{message}
</div>
)
}
Instead, wrap the instantiation of WebSockets with a useEffect (such that it only triggers once, and is disconnected when the component is unmounted).
import React, {useEffect, useState} from 'react'
import { io } from "socket.io-client";
export default function MockSocket() {
const [message, setMessage] = useState("");
useEffect(
() => {
const socket = io();
socket.connect();
socket.on("recieve_message", setMessage);
return () => {
socket.disconnect();
}
},
[]
)
return (
<div>
{message}
</div>
)
}
Upvotes: 12