6

I'am creating a chat application using React.js,node and socket.io. Its working absolutely fine for initial 2-3 requests but after that the device hangs for infinity.

i think the problem is with my code logic. here is my front end:

import React from "react";
import SendIcon from "@material-ui/icons/Send";
import "./chat.css";
import queryString from "query-string";
import { useEffect } from "react";
import { userName, roomId } from "./login.jsx";
import { useLocation } from "react-router-dom";
import { useState } from "react";
import chat from "./chat.svg";
import TextField from "@material-ui/core/TextField";
import AccountCircleSharpIcon from "@material-ui/icons/AccountCircleSharp";
import FingerprintSharpIcon from "@material-ui/icons/FingerprintSharp";
import io from "socket.io-client";

let socket;

function Chat() {
  let [name, setName] = useState();
  let [room, setRoom] = useState();
  let [childWidth, setChildWidth] = useState({ width: "50vw" });
  let [btnColor, setBtnColor] = useState({ fontSize: "4vmax" });
  let [joined, setJoined] = useState([]);

  const ENDPOINT = "http://localhost:5000";

  socket = io(ENDPOINT);

  const search = useLocation().search;
  let name1 = new URLSearchParams(search).get("name");
  let room1 = new URLSearchParams(search).get("id");

  useEffect(() => {
    setName(new URLSearchParams(search).get("name"));
    setRoom(new URLSearchParams(search).get("id"));
    if (window.innerWidth <= 1080) {
      setChildWidth({ width: "100%", height: "100%" });
      setBtnColor({ fontSize: "6vmax" });
    }

    socket = io(ENDPOINT);

    socket.emit("userName", { name1, room1 });
  }, [name, room]);

  useEffect(() => {
    socket.on("userName", (payload) => {
      setJoined([...joined, payload.name1]);
    });
  }, [joined]);

  return (
    <>
      <main id="main_chat">
        <section id="child_child" style={childWidth}>
          <header id="header_child">
            <div id="username_roomid">
              <p id="user_name">
                <span id="user_logo">
                  {" "}
                  <AccountCircleSharpIcon />
                </span>{" "}
                <span id="name_of_user">{name}</span>
              </p>
              <p id="room_name">
                <span id="room_logo">
                  <FingerprintSharpIcon />
                </span>{" "}
                <span id="id_of_room">{room}</span>
              </p>
            </div>

            <div id="logo_name">
              <img src={chat} />
              <h2>R Chat</h2>
            </div>
          </header>
          <section id="msg_area">
            {joined.map((value) => {
              return <p>{value} has joined</p>;
            })}
          </section>

          <footer id="footer_child">
            <div id="footer_input_child">
              <TextField
                id="msg_input"
                label="Enter a message"
                variant="outlined"
                fullWidth
              />
            </div>

            <div id="footer_button_child">
              <SendIcon id="send_button" style={btnColor} />
            </div>
          </footer>
        </section>
      </main>
    </>
  );
}

export default Chat;

here is my server using express:

const express = require("express");
const socketio = require("socket.io");
const http = require("http");
const cors = require("cors");

const PORT = process.env.PORT || 5000;

const router = require("./router");

const app = express();

const server = http.createServer(app);

const io = socketio(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
    transports: ["websocket", "polling"],
    credentials: true,
  },
  allowEIO3: true,
});

io.on("connection", (socket) => {
  console.log("we have a new connection");

  socket.on("userName", (payload) => {
    console.log(payload);
    io.emit("userName", payload);
    // socket.broadcast.emit('userName',payload);
  });

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

app.use(router);
app.use(cors());

server.listen(PORT, () =>
  console.log(`The server is listening at port ${PORT}`)
);

here is the error

console error

Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
Rohit Sahu
  • 61
  • 3
  • 1
    Does this answer your question? [Infinite loop in useEffect](https://stackoverflow.com/questions/53070970/infinite-loop-in-useeffect) – Janez Kuhar Aug 20 '21 at 10:38

0 Answers0