0

I am making a simple chat app. However I have run into a problem. My router state is only defined when useEffect runs twice. I am using express and react for a simple "join" page. So for example I have Join.js that you can input the room and name, which sends to Chat.js. For example, the App.js

const App = () => (
    <Router>
       <Routes>
        <Route path="/" exact element={<Join/>}/>
        <Route path="/chat" element={<Chat/>}/>
      </Routes>
    </Router>
);

Join.js

const Join = () => {
    const [name, setName] = useState('');
    const [room, setRoom] = useState('');

    const makeInput = (text, func) => {
        return (
            <div>
                <input placeholder={text} className="joinInput" type="text" onChange={func} />
            </div>
        );
    }

    const handleName = (event) => {
        setName(event.target.value);
    }

    const handleRoom = (event) => {
        setRoom(event.target.value);
    }

    return (
        <div className="joinOuterContainer">
            <div className="joinInnerContainer">
                <h1 className="heading">Join</h1>
                    {makeInput("Name", handleName)}
                    {makeInput("Room", handleRoom)}
                <Link
                    onClick={event => (!name || !room) && event.preventDefault()}
                    to={`/chat?name=${name}&room=${room}`}
                    state={{ name: {name}, room: {room} }}
                >
                    <button className="button mt-20" type="submit"> Sign In </button>
                </Link>
            </div>
        </div>
    )
}

The problem is in Chat.js:

const Chat = () => {

    const [name, setName] = useState('');
    const [room, setRoom] = useState('');

    const location = useLocation();
    const ENDPOINT = 'localhost:5000';

    useEffect(() => {

        setName(location.state.name.name);
        setRoom(location.state.room.room);

        console.log("Name: " + name + "Room: " + room);


    }, []);

    return (
        <h1>Chat</h1>
    )
}

As you can see, I want to log the "name" and the "room" once I get to Chat.js. The problem is, it only works if it runs twice. Right now in the console I get

Name: Room:

when it should have values. However in useEffect if I take out the "[]" so that it runs more than once, it works perfectly. How do I fix this?

  • tl;dr; `console.log("Name: " + location.state.name.name+ "Room: " + location.state.room.room);` or move your console log outside of the effect – Konrad Nov 25 '22 at 18:13
  • Btw if you want to have these values only once, you do not need a `useEffect`. You can simply initialize your states with `location`. Ie. `const [room, setRoom] = useState(location.state.room.room)` – dbuchet Nov 25 '22 at 19:04

0 Answers0