Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
React stat and Socket.io

I have this component in which I want to update a state and make an array with al the users connected in a room from an incoming msg from socket.on:

export default function ChatRoom() {
  const [users, setUsers] = useState([]);
  const { state } = useLocation(); //to get data from <Home/> component


  socket.on("message", (msg) => console.log(msg));

  useEffect(() => {
    if (state.connected) {
      socket.on("userconnected", (msg) => {
        setUsers((old) => [...old, msg]);

        console.log(state.username);
      });
    }
  }, [state.connected, users]);

The username is coming from another component state in which I send a msg to the server:

export default function Home() {
  const [username, setUsername] = useState("");
  const [room, setRoom] = useState("");
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    if (connected && room && username) {
      navigate("/chatroom", {
        state: { username, room, connected },
      });
    }
  }, [connected, room, username]);

  const navigate = useNavigate();

  const handleClick = (e) => {
    e.preventDefault();
    socket.emit("connected", username);
    setConnected(true);
  };

The problem is that I cant update the state with setUsers. I think it has to do with an async problem but I can´t figure it out. Basically I need an array with all the users that are connected.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!