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

CountDown is not rendering correctly on React

I have a chat app on React and when chat can not connect, reconnect modal (ant d) is opened

enter image description here

And I want that, when I click the ”reconnect“` button, the countdown must work. But it only works when I click, and after it stops.

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

I think React can not render because on the console it repeats.

enter image description here

Maybe it depends on Websocket.

My codes

  const [countDown, setCountDown] = useState(60);
  const [reconnectModal, setReconnectModal] = useState(false);

  const reconnectFunction = () => {
    connect(); // connect is for Websocket. I can connect the chat with this function.
    setInterval(() => {
      setCountDown(countDown - 1);
    }, 1000);
  };

    <Modal
        visible={reconnectModal}
        okText={`Reconnect ${`(${countDown})`}`}
        cancelText="Close"
        onOk={reconnectFunction}
        onCancel={() => setReconnectModal(false)}
      >
        Connection failed. Please try again
    </Modal>

>Solution :

It is because when you set the interval it will convert the countDown with the actual value (default here is 60).
So when it update the value of countDown, it will not update this value in the interval.

I think you can simply change to :

setInterval(() => {
  setCountDown((v) => v - 1);
}, 1000);

As the v is always the last value of the state.

Working example here.

Don’t forget to handle when the count is at 0. And maybe have the interval in a ref to cancel it when you are connected and therefore no need to continue the interval.

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