Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Async onClick Event

I´m trying to update a state inside this:

const [username, setUsername] = useState("");
  const [room, setRoom] = useState("");
  const [connected, setConnected] = useState(false);

  const navigate = useNavigate();

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

    setConnected(true);
    console.log(connected);
    navigate("/chatroom", {
      state: { username, room, connected },
    });
  };

<button
            type="submit"
            className="btn"
            onClick={(e) => {
              handleClick(e);
            }}
          >

The problem is that the state is not updating when I click. I know is an async problem, but I´ve tried the other options asked in SO but I dont get it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have 2 ways to fix

The first one is using useEffect to listen to connected, username, and room values changes

const [username, setUsername] = useState("");
  const [room, setRoom] = useState("");
  const [connected, setConnected] = useState(false);

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

  const navigate = useNavigate();

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

    setConnected(true);
    
  };

The 2nd way, you can use class-based component instead of function-base component and then call setState with callback. Here is an example

setState({
  connected: true,
  username: "updated username",
  room: "updated room"
}, () => {
   navigate("/chatroom", {
      state: { username, room, connected },
    });
});

You can check the document here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading