how to useHook for d-day count in react?

69 Views Asked by At

When I clicked a post, the screen will navigates to 'post detail screen'. In 'post detail screen', there are timer that calculates times between present time and future time.

I have done timer function, and it well done !

But, When i clicked a post,

When you do it for the first time, 0: 0: 0: 0 comes out, the time to be re-rendered, 34: 11: 32: 23

How can i fix this 0:0:0:0? I want to have it come out immediately at the same time as 34: 11: 32: 23

... react function component...

 const [day, setDay] = useState<string | number>(0);
  const [hour, setHour] = useState<string | number>(0);
  const [min, setMin] = useState<string | number>(0);
  const [sec, setSec] = useState<string | number>(0);

  const calcuateGapBetweenDates = () => {
    const b1 = new Date();
    const b2 = new Date(endDate);  // endDate = 2021-03-30T17:00:00.000Z
    const c1 = b1.getTime(); // 1613582634000
    const c2 = b2.getTime(); // 1613582634000
    const gap = c2 - c1;

    setDay(() => {
      const temp = Math.ceil(gap / (1000 * 60 * 60 * 24));
      return temp < 10 ? `0${temp}` : temp;
    });

    setHour(() => {
      const temp = Math.ceil((gap % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      return temp < 10 ? `0${temp}` : temp;
    });

    setMin(() => {
      const temp = Math.ceil((gap % (1000 * 60 * 60)) / (1000 * 60));
      return temp < 10 ? `0${temp}` : temp;
    });

    setSec(() => {
      const temp = Math.ceil((gap % (1000 * 60)) / 1000);
      return temp < 10 ? `0${temp}` : temp;
    });
  };

  useLayoutEffect(() => {
    const setIntervalForEverySecond = setInterval(() => {
      calcuateGapBetweenDates();
    }, 1000);
    return () => clearInterval(setIntervalForEverySecond);
  }, []);

return ( 
      <View>
         <Text>
            {day} :
            {hour}:
            {min}:
            {sec}
          </Text>
      </View>
)
1

There are 1 best solutions below

0
On

You initialize your states values with 0, that's why when the screen is loaded you will see

0: 0: 0: 0

  const [day, setDay] = useState<string | number>(0);
  const [hour, setHour] = useState<string | number>(0);
  const [min, setMin] = useState<string | number>(0);
  const [sec, setSec] = useState<string | number>(0);

thus, right after your states are being changed (using setDay, setHour etc') the value is no longer the initial value, but the new value.

in order to fix this issue, you will have to initialize your states with the desired value