Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
How to use socket.on in react?

I am building a small chat app, but I have problems with receiving messages in react. The problem is that when I receive a message I setMessages, but at the same time the messages state gets cleared. The problem is problably that I don't know where to place socket.on, currently it's inside a useEffect hook.

export const Room = ({ socket }) => {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");
  const { id } = useParams();
  
  useEffect(() => {
    socket.emit("join room", id);
  }, []);

  useEffect(() => {
    socket.on("message", (message) => {
      setMessages([
        ...messages,
        { message: message, createdBy: "other", id: uuidv4() },
      ]);
    });
  }, []);
  const sendMessage = () => {
    console.log("send");
    socket.emit("message", input);
    setMessages([
      ...messages,
      { message: input, createdBy: "me", id: uuidv4() },
    ]);
  };
  console.log("foo");
  return (
    <div className="flex justify-center text-center">
      <div className="w-screen h-screen px-2 max-w-4xl mt-10">
        <p className="text-3xl">Code: {id}</p>
        <div className="bg-white w-full h-3/4 rounded-xl border-2 border-black overflow-y-auto">
          {messages.map((message) => (
            <Message
              text={message.message}
              createdBy={message.createdBy}
              key={message.id}
            />
          ))}
        </div>
        <div className="flex flex-row border-2 border-black mt-2 rounded-xl p-2 bg-white">
          <input
            className="flex-grow border-none focus:outline-none"
            onInput={(e) => setInput(e.target.value)}
          />
          <button
            className=" bg-green-500 rounded-xl px-2 py-1"
            onClick={sendMessage}
          >
            Send
          </button>
        </div>
      </div>
    </div>
  );
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I'm pretty sure you have a closure problem. messages is not what you think it is when it is run inside the useEffect -- it may not be the latest version.

It's safer and good practice to use the functional variant of the setter. This way you can be certain that messages is the current version:

setMessages(messages => [
  ...messages,
  { message: message, createdBy: "other", id: uuidv4() },
]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda