So I'm learning socket.io with react, and I'm encountering an issue. What I want to happen is that when a user inputs something into the field and submits it, it makes the title of everyone's browser that input. However, if your text field is equal to the message spread with everyone (meaning it was probably you who clicked enter) it'll make your title 'You changed it'.
However, it seems that in io.on(message), when it checks if the input state is equal to the message, it always checks the initial value of the state against the message, which is ''.
I'm guessing this happens because useEffect is called at the beginning when the state is '', so it hard codes the io.on(message) to be what the state is at that time. I thought to fix this i'd just make input a part of useEffect's dependancy array, but that doesn't override the current io.on(message), it overloads it, so both are called. Don't know how to fix this!
import React from 'react'
import io from 'socket.io-client'
const SocketTest = (props: any) => {
const socket = io('http://localhost:4000')
const [input, setInput] = React.useState<string>('')
const handleNewMessage = (message: string) => {
console.log(input)
if (input !== message){
document.title = message
} else {
document.title = 'You changed it!'
}
}
React.useEffect(() => {
socket.on('message', (message: string) => {
handleNewMessage(message)
})
}, [])
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInput(e.target.value)
}
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
socket.emit('message', input)
}
return (
<div>
<h2 className="center">{ input }</h2>
<form onSubmit={ (e) => handleSubmit(e) }>
<input type="text" placeholder="Enter text" onChange={ (e) => handleChange(e) }/>
</form>
</div>
)
}
export default SocketTest
I'm also sure I could fix this by broadcasting the message instead of emitting it, but I'm moreso trying to learn how to fix that issue.