Home > Software engineering >  CountDown is not rendering correctly on React
CountDown is not rendering correctly on React

Time:02-05

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.

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>

CodePudding user response:

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.

  • Related