I'm building a dummy chat app to know how socket.io works (with react and node. Everything seems to work fine except that socket io emits more than one message.
It looks like for each character I type when then I press on submit it emits the message multiplying the total of characters per 2.
How can I solve this?
Thank you!
Client
import React from "react";
import { useState } from "react";
import { io } from "socket.io-client";
const App = () => {
const socket = io("http://localhost:5000");
const [input, setInput] = useState("");
const handleChange = (e) => {
setInput(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
socket.emit("chat-message", input);
};
socket.on("chat-message", (msg) => {
console.log(msg);
});
return (
<div className="App">
<h1>Chat</h1>
<form onSubmit={handleSubmit}>
<input onChange={handleChange} type="text" id="input" />
<button type="submit">Send</button>
</form>
<div id="messages">
</div>
</div>
);
};
export default App;
Server
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: '*',
}
});
io.on('connection', (socket) => {
socket.on('chat-message', (msg) => {
io.emit('chat-message', msg);
})
});
server.listen(5000, () => {
console.log('listening on: 5000');
});