Skip to content

Commit

Permalink
Add Send Button and Send Message
Browse files Browse the repository at this point in the history
  • Loading branch information
stanleyowen committed Nov 7, 2020
1 parent 6af1074 commit 4201ba8
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
32 changes: 29 additions & 3 deletions client/src/components/Chat/Chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ let socket;
const Chat = ({location}) => {
const [name, setName] = useState('');
const [room, setRoom] = useState('');
const [message, setMessage] = useState([]);
const [messages, setMessages] = useState([]);
const ENDPOINT = 'localhost:5000'
useEffect(() => {
const {name, room} = queryString.parse(location.search);
Expand All @@ -14,17 +16,41 @@ const Chat = ({location}) => {
setName(name);
setRoom(room);

socket.emit('join', { name, room }, ({ error }) => {
socket.emit('join', { name, room }, () => {

});

return () => {
socket.emit('disconnect');
socket.off();
}
}, [ENDPOINT, location.search])
}, [ENDPOINT, location.search]);

useEffect(() => {
socket.on('message', (message) => {
setMessage([...messages, message])
})
}, [messages]);

const sendMessage = (event) => {
event.preventDefault();
if(message) {
socket.emit('sendMessage', message, () => setMessage(''));
}
};

console.log(message, messages)

return (
<h1>Chat</h1>
<div className="outerContainer">
<div className="container">
<input
value={message}
onChange={(event) => setMessage(event.target.value)}
onKeyPress={event => event.key === 'Enter' ? sendMessage(event) : null}
/>
</div>
</div>
)
}

Expand Down
2 changes: 1 addition & 1 deletion server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ io.on('connection', (socket) => {
socket.join(user.room);

socket.emit('message', { user: 'admin', text: `${user.name}, welcome to the room ${user.room}` });
socket.broadcast.to(ser.room).emit('message', { user: 'admin', text: `${user.name}, welcome to the room ${user.room}` })
socket.broadcast.to(user.room).emit('message', { user: 'admin', text: `${user.name}, welcome to the room ${user.room}` })

callback();

Expand Down
2 changes: 1 addition & 1 deletion server/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const users = [];
const addUser = ({ id, name, room }) => {
name = name.trim().toLowerCase();
room = name.trim().toLowerCase();
const existingUser = user.find((user) => user.name === name && user.room === room);
const existingUser = users.find((user) => user.room === room && user.name === name);
if(existingUser) {
return { error: 'Username is Taken, Please Try Another Username' }
}
Expand Down

0 comments on commit 4201ba8

Please sign in to comment.