V
V
Vladimir2021-06-24 00:30:13
Socket.io
Vladimir, 2021-06-24 00:30:13

Why does the component assign all messages to the current client?

Hello. Please tell me what could be the reason for this behavior? I am writing a chat, I took the source code of the front on the react from the gita. Added a chat socket to it, but it does not work as I would like.

Front with Gita

Back:

const app = require("express")();
const httpServer = require("http").createServer(app);
const options = {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
};
const io = require("socket.io")(httpServer, options);

io.on("connection", socket => {

    console.log(socket.id);

    socket.on('disconnect', () => {
        console.log('user disconnected');
    });

    socket.on('message', message => {
        io.emit('showMessage', message);
    });

});

app.get('/', (req, res) => {
    res.send({data: 'Okay'}).status(200);
});

httpServer.listen(4001);


Component:

import React, {useEffect, useState} from 'react';
import Compose from '../Compose';
import Toolbar from '../Toolbar';
import ToolbarButton from '../ToolbarButton';
import Message from '../Message';
import moment from 'moment';
import './MessageList.css';

import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:4001/";

const socket = socketIOClient(ENDPOINT);


export default function MessageList(props) {
  const [messages, setMessages] = useState([]);

  const tempMessages = [];

  useEffect(() => {

    socket.on("connect", () => {

      console.log(socket.id);

    });

    socket.on('showMessage', message => {

      tempMessages.push(
          {
            id: Math.random(),
            author: socket.id,
            message: message,
            timestamp: new Date().getTime()
          }
      );

      getMessages(tempMessages);

      console.log(tempMessages);

    });

  },[]);


  const getMessages = (msg) => {

      setMessages([...messages, ...msg]);

  }

  const renderMessages = () => {
    let i = 0;
    let messageCount = messages.length;
    let tempMessages = [];

    while (i < messageCount) {
      let previous = messages[i - 1];
      let current = messages[i];
      let next = messages[i + 1];
      let isMine = current.author === socket.id;
      let currentMoment = moment(current.timestamp);
      let prevBySameAuthor = false;
      let nextBySameAuthor = false;
      let startsSequence = true;
      let endsSequence = true;
      let showTimestamp = true;

      if (previous) {
        let previousMoment = moment(previous.timestamp);
        let previousDuration = moment.duration(currentMoment.diff(previousMoment));
        prevBySameAuthor = previous.author === current.author;

        if (prevBySameAuthor && previousDuration.as('hours') < 1) {
          startsSequence = false;
        }

        if (previousDuration.as('hours') < 1) {
          showTimestamp = false;
        }
      }

      if (next) {
        let nextMoment = moment(next.timestamp);
        let nextDuration = moment.duration(nextMoment.diff(currentMoment));
        nextBySameAuthor = next.author === current.author;

        if (nextBySameAuthor && nextDuration.as('hours') < 1) {
          endsSequence = false;
        }
      }

      tempMessages.push(
        <Message
          key={i}
          isMine={isMine}
          startsSequence={startsSequence}
          endsSequence={endsSequence}
          showTimestamp={showTimestamp}
          data={current}
        />
      );

      // Proceed to the next message.
      i += 1;
    }

    return tempMessages;
  }

    return(
      <div className="message-list">
        <Toolbar
          title="Messanger"
          rightItems={[
            <ToolbarButton key="info" icon="ion-ios-information-circle-outline" />,
            <ToolbarButton key="video" icon="ion-ios-videocam" />,
            <ToolbarButton key="phone" icon="ion-ios-call" />
          ]}
        />

        <div className="message-list-container">{renderMessages()}</div>

        <Compose rightItems={[
          <ToolbarButton key="photo" icon="ion-ios-camera" />,
          <ToolbarButton key="image" icon="ion-ios-image" />,
          <ToolbarButton key="audio" icon="ion-ios-mic" />,
          <ToolbarButton key="money" icon="ion-ios-card" />,
          <ToolbarButton key="games" icon="ion-logo-game-controller-b" />,
          <ToolbarButton key="emoji" icon="ion-ios-happy" />
        ]}/>
      </div>
    );
}


It assigns the socket id of the current client when sending messages, to all messages. How to fix it?



0: {id: 0.8027327004825733, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp:1624483588783}
1: {id: 0.6056099262860521, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483589690}
2: {id : 0.11380354097618484, author: "eknt9RjpM07f6LPcAACQ" , message: "asdasd", timestamp:1624483589925}
3: {id: 0.03147155705252702, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483590080}
4: {id: 0.3803585117922945, author : "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483590213
}author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483599119}
7: {id: 0.4798664574785938, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp:1624483599277}
8: {id: 0.13681540277126292, author: "eknt9RjpM07f6LPcAACQ", message: "asdasd", timestamp: 1624483599408}
length: 9
__proto__ : array(0)



Thank you.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question