Reputation: 151
I am learning react js and am making a chat app using socket.io But I have run into this issue where it logs increasing number of times per message
This is my code for socketio stuff
import React, { useState } from 'react'
import io from "socket.io-client"
const socket = io("https://Wyvern-API.huski3.repl.co/api/chat")
socket.on('connect', () => {
socket.emit('joined', { 'serverchannel': 120 })
console.log("Connected")
})
function socketio() {
const [hello, setCount] = useState("0")
socket.on('message', (data) => {
setCount(data.content)
console.log(data.content)
})
return (
<div>
<h1>{hello}</h1>
</div>
)
}
export default socketio
I used useEffect to stop it from spamming the ui during testing however I dont know how to address the root of this issue
Upvotes: 1
Views: 4379
Reputation: 287
Put all of your socketio listeners inside useEffect. React renders multiple times when any state or data changes, If your socket io listeners are outside useEffect , they will be added multiple times and so multiple triggers.
import React, { useState } from 'react'
import io from "socket.io-client"
function socketio() {
const [hello, setCount] = useState("0")
const [socket, setSocket] = useState(null)
useEffect(()=>{
if(socket === null)
{
setSocket(io("https://Wyvern-API.huski3.repl.co/api/chat"))
}
if(socket)
{
socket.on('connect', () => {
socket.emit('joined', { 'serverchannel': 120 })
console.log("Connected")
})
socket.on('message', (data) => {
setCount(data.content)
console.log(data.content)
})
}
},[socket])
return (
<div>
<h1>{hello}</h1>
</div>
)
}
export default socketio
Upvotes: 5