iam new to the websocket, and i'm currently wanting to create a chat app using socket.io i follow the documentation on the socket.io website and successfully connect the server to the client but as i want to emit from the server to the client or vise versa i found out that my client is not connected to the server as the property disconnected = true
and my guess is that because of this i can't use the emit event can someone explain whats going on?
note: both using version 2.2.0 of socket.io
here is the screenshot of whats happening
and the code of the server
const app = require('express')()
const http = require('http').createServer(app)
const io = require('socket.io')(http)
io.on('connection', socket => {
console.log(socket.connected)
socket.on('message', ({ name, message }) => {
console.log(name)
console.log(message)
io.emit('message', { name, message })
})
})
http.listen(4000, function () {
console.log('listening on port 4000')
})
and here is the screenshot of the client
and here is the code of the client
import React, { useEffect, useRef, useState } from "react"
import io from "socket.io-client"
import "./App.css"
function App() {
const [state, setState] = useState({ message: "", name: "" })
const [chat, setChat] = useState([])
const socketRef = useRef()
useEffect(
() => {
socketRef.current = io("http://127.0.0.1:4000")
socketRef.current.connect()
console.log(socketRef.current)
socketRef.current.on('connect', function () {
console.log("masuk")
});
socketRef.current.on("message", ({ name, message }) => {
setChat([...chat, { name, message }])
})
return () => socketRef.current.disconnect()
},
[chat]
)
const onTextChange = (e) => {
setState({ ...state, [e.target.name]: e.target.value })
}
const onMessageSubmit = (e) => {
const { name, message } = state
console.log(name)
console.log(message)
socketRef.current.emit("message", { name, message })
e.preventDefault()
setState({ message: "", name })
}
const renderChat = () => {
return chat.map(({ name, message }, index) => (
<div key={index}>
<h3>
{name}: <span>{message}</span>
</h3>
</div>
))
}
return (
<div className="card">
<form onSubmit={onMessageSubmit}>
<h1>Messenger</h1>
<div className="name-field">
<TextField name="name" onChange={(e) => onTextChange(e)} value={state.name} label="Name" />
</div>
<div>
<TextField
name="message"
onChange={(e) => onTextChange(e)}
value={state.message}
id="outlined-multiline-static"
variant="outlined"
label="Message"
/>
</div>
<button>Send Message</button>
</form>
<div className="render-chat">
<h1>Chat Log</h1>
{renderChat()}
</div>
</div>
)
}
export default App