project_chat_application
project_chat_application copied to clipboard
sendMessage function not working
When I click on send button, nothing happens. sendMessage method is not working neither I am getting messages from admin. Is it an issue of socket.io ?
same error, sometimes I can sent,message but sometimes I can't
share your code maybe i can help
Same error, do you already have some answer?
For me also this error
I had the same issue. I wrote wrong inside of io.to.
It will be user.room
. io.to(user.room).emit("message", { user: user.name, text: message });
Another thing is to be careful about setMessages
in useEffect
.
useEffect(() => {
socket.on("message", (message) => {
console.log("BACK FROM EMIT");
setMessages((messages) => [...messages, message]);
});
return () => {
socket.off();
};
}, []);
I added a console.log to useEffect. If sendMessage
function in index.js is working properly, this useEffect and console.log will work.
I hope this works for you.
I've been console.logging this for a while and find out, that we have different id
s for user in array, and id
we're sending to the getUser(id)
function, can't get why
Found the solution here: https://stackoverflow.com/a/68330672/14385332
Simply created new file: client>src>helpers>socket.js
import { io } from 'socket.io-client'
const ENDPOINT = 'http://localhost:5000/'
export const socket = io(ENDPOINT)
export let socketID = ''
socket.on('connect', () => {
socketID = socket.id
})
Then inside Chat.js
:
import React, { useState, useEffect } from 'react'
import queryString from 'query-string'
import { socket } from '../../helpers/socket'
import InfoBar from '../InfoBar/InfoBar'
import Input from '../Input/Input'
import Messages from '../Messages/Messages'
import TextContainer from '../TextContainer/TextContainer'
import './Chat.css'
const Chat = ({ location }) => {
const [name, setName] = useState('')
const [room, setRoom] = useState('')
const [message, setMessage] = useState('')
const [messages, setMessages] = useState([])
...