最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible that emitting an event is listened by the frontend itself in socket.io - Stack Overflow

programmeradmin2浏览0评论

I'm working on a React-based chat widget that uses socket.io for real-time communication. In my handleSendMessage function, I'm emitting a message event using socket.emit. However, I'm also listening for the message event on the frontend with socket.on("message") inside a useEffect.

The issue is that the message event listener is being triggered by the same message event emitted from the handleSendMessage function, even though it is intended only for events emitted by the backend. This causes the payload I emit in handleSendMessage to be received directly in the socket.on("message") listener.

Additionally, my handleMessage function (which updates the state with new messages) is not being invoked as expected.

import { useEffect, useState } from "react";
import { MessageCircle, Send, X, Minus, MessageCircleX } from "lucide-react";
import "./ChatWidget.css";
import axios from "axios";
import { v4 as uuid } from "uuid";

const ChatWidget = ({ socket }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [isMinimized, setIsMinimized] = useState(false);
  const [messages, setMessages] = useState([]);
  const [newMessage, setNewMessage] = useState("");
  const [widgetStyles, setWidgetStyles] = useState(null);
  const [chatDetails, setDetailsDetails] = useState(null);

  const workspaceId = localStorage.getItem("widget_workspaceId") || null;
  let visitor = JSON.parse(localStorage.getItem("visitor"));

  useEffect(() => {
    axios
      .get(`http://localhost:3010/api/widget-settings/${workspaceId}`)
      .then((res) => {
        if (res.data.data.theme) {
          setWidgetStyles(res.data.data.theme);
        }
      })
      .catch((err) => {
        console.log("Error while fetching styles for widget ->", err);
      });
  }, []);

  useEffect(() => {
    axios
      .get(
        `http://localhost:3010/api/visitor-details/${workspaceId}/${visitor.visitorId}`
      )
      .then((res) => {
        setDetailsDetails(res.data.data);
      });
  }, []);

  const handleSendMessage = (e) => {
    e.preventDefault();

    if (!newMessage) {
      return;
    }

    console.log("CHAT DETAILS ->", chatDetails);

    if (!chatDetails) {
      socket.emit(
        "visitor-message-request",
        {
          workspaceId,
          visitor,
        },
        (response) => {
          console.log("VISITOR MESSAGE REQUEST GETTING TRIGGERED");

          if (response.chatId) {
            socket.emit("message", {
              message: { content: newMessage },
              chatId: response.chatId,
              sender: { ...visitor, type: "visitor" },
              to: workspaceId,
            });
          }
        }
      );
    }

    socket.emit("message", {
      message: { content: newMessage },
      chatId: chatDetails.id,
      sender: { ...visitor, type: "visitor" },
      to: workspaceId,
    });

    setNewMessage("");
    // }
  };

  const handleMessage = (message) => {
    console.log("Message received ->", message);
    setMessages((prevMessages) => [...prevMessages, message]);
  };

  useEffect(() => {
    socket.on("message", handleMessage);

    return () => {
      socket.off("message", handleMessage);
    };
  }, []);

  return (
    <div className="chat-container">
      <div className="chat-button-wrapper">
        {isOpen && (
          <div className={`chat-window ${isMinimized ? "minimized" : ""}`}>
            <div className="chat-header">
              <div className="chat-title">
                <MessageCircle
                  style={{ color: widgetStyles.logoColor || "#3BA9E5" }}
                />
                <span>Chat with us</span>
              </div>
              <div className="chat-controls">
                <button onClick={() => setIsMinimized(!isMinimized)}>
                  <Minus />
                </button>
                <button onClick={() => setIsOpen(false)}>
                  <X />
                </button>
              </div>
            </div>

            {!isMinimized && (
              <>
                <div className="chat-messages">
                  {messages.map((message) => (
                    <div
                      key={message.id}
                      className={`message-wrapper ${message.sender.type}`}
                    >
                      {/* {console.log(message)} */}
                      <div className="message">{message.content}</div>
                    </div>
                  ))}
                </div>

                <form onSubmit={handleSendMessage} className="chat-input-form">
                  <input
                    type="text"
                    value={newMessage}
                    onChange={(e) => setNewMessage(e.target.value)}
                    placeholder="Type a message..."
                  />
                  <button
                    type="submit"
                    style={{
                      backgroundColor:
                        widgetStyles.sendButtonBackgroundColor || "#3BA9E5",
                    }}
                  >
                    <Send />
                  </button>
                </form>
              </>
            )}
          </div>
        )}
        <button
          onClick={() => setIsOpen(!isOpen)}
          className={`chat-toggle-button ${isOpen ? "active" : ""}`}
          style={{
            backgroundColor: widgetStyles?.backgroundColor || "#3BA9E5",
            color: widgetStyles?.textColor || "#ffffff",
          }}
        >
          {isOpen ? <MessageCircleX /> : <MessageCircle />}
        </button>
      </div>
    </div>
  );
};

export default ChatWidget;
发布评论

评论列表(0)

  1. 暂无评论