project_chat_application icon indicating copy to clipboard operation
project_chat_application copied to clipboard

sendMessage function not working

Open rajkamal96 opened this issue 4 years ago • 7 comments

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 ?

rajkamal96 avatar Jun 21 '20 01:06 rajkamal96

same error, sometimes I can sent,message but sometimes I can't

zyphuscode avatar Jun 22 '20 09:06 zyphuscode

share your code maybe i can help

Rupamdas832 avatar Jun 28 '20 06:06 Rupamdas832

Same error, do you already have some answer?

josethz00 avatar Aug 13 '20 21:08 josethz00

For me also this error

logicalTanz1008 avatar Dec 16 '20 09:12 logicalTanz1008

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.

mehdisolhan avatar Mar 28 '21 20:03 mehdisolhan

I've been console.logging this for a while and find out, that we have different ids for user in array, and id we're sending to the getUser(id) function, can't get why

T-Damer avatar Aug 23 '21 16:08 T-Damer

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([])

...

T-Damer avatar Aug 23 '21 16:08 T-Damer