SocketIO client side io.connect does not connect to server when reloading the page and checking for cached values

This frontend goes from enter username -> create/join lobby. When following this path, it works fine and the socket is connected. If the user previously entered a username, the initial username page is not loaded and skips to the create/join lobby.

From here, it should connect, as it checks if the use state value of userID is not null, and connect.

App.js

import { useEffect, useState } from 'react';
import UsernameComponent from './components/usernameComponent';
import socket from './socket';


function App() {
  const [sessionId, setSessionId] = useState(sessionStorage.getItem("sessionId"));
  const [userID, setUserID] = useState(sessionStorage.getItem("userID"));
  const [room, setRoom] = useState('');
  const [inputValue, setInputValue] = useState("");
  console.log(userID);
  useEffect(() => {
    if (sessionId.length > 0) {
      socket.auth = { sessionId };
      console.log(socket);
    }
  }, [sessionId]);

  socket.on('connect', function () {
    console.log(socket.connected);
    socket.emit('refresh');
  });

  socket.on('connect', () => {
    console.log("Socket connected woo");
  });

  const onChangeHandler = event => {
    setInputValue(event.target.value);
  };

  const createLobby = () => {
    console.log(socket);
    socket.emit("Create-Room", inputValue, reply => {
      console.log(reply);

    });
  }
  
  return (
    <>
      {userID == null && sessionId == null && <UsernameComponent sessionId={sessionId} setSessionId={setSessionId} userID={userID} setUserID={setUserID} />}
      <div className='flex flex-col justify-center h-screen  w-6/12 mr-auto'>
        <div className='flex flex-row justify-evenly items-center'>
          <input type="text" className='border' onChange={onChangeHandler}></input>
          <button onClick={() => createLobby}>Create Lobby</button>
        </div>
        <div className='flex flex-row justify-evenly items-center'>
          <input type="text" className='border' onChange={onChangeHandler}></input>
          <button>Join Lobby</button>
        </div>
      </div>
    </>
  );
}

export default App;

usernameComponenet.js

import './../App.css';
import { useEffect, useState } from 'react';

const UsernameComponent = ({ socket, sessionId, setSessionId, userID, setUserID, setUsername, username}) => {


    const onUsernameSubmission = (username) => {
        socket.auth = { username };
        socket.connect();
        console.log(socket);
    }

    useEffect(() => {


        socket.on('session', (sessionInformation)=> {
            console.log(sessionInformation);
            sessionStorage.setItem("sessionId", sessionInformation.sessionID);
            sessionStorage.setItem("userID", sessionInformation.userID);
            setSessionId(parseInt(sessionInformation.sessionID)); // Parse to integer
            setUserID(parseInt(sessionInformation.userID)); // Parse to integer
        });
        console.log(' this runs as it should');

        socket.on('connection', () => {
            console.log('Connected to the server');
        });

    }, []);

    return (
        <div className="h-screen min-h-screen flex justify-center">
            <div className="flex flex-col justify-center items-center content-around">
                <input className="border" type="text" value={username} onChange={e => setUsername(e.target.value)}/>
                <button className="border" onClick={() => onUsernameSubmission(username)}>Click me!</button>
            </div>              
        </div>  
    );
}

export default UsernameComponent;

Socket Creation

import { io } from "socket.io-client";

const URL = "http://localhost:3000";
const socket = io(URL, { autoConnect: false });

export default socket;

I’ve moved socket.connect() outside use effect, ran it several times. Connection is always false. Tried passing from app to usernameComponenet via props, but didn’t work. The function that connect is in does run, but does not connect or give a console error/any backend response.

New contributor

Tski is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật