0

I have app for booking. User can select days and book it, User has 30 min to pay this reservation. If user doesn't pay it, reservation will be automatically deleted. Here is problem, When I have open app and current page with booking details and time is finished, reservation is deleted, all is working, BUT if this page is closed, reservation is still there. Time is still running, reservation in mongo is not deleted. Can you please tell me what I am doing wrong? Is it because in useEffect window.setInterval... ? here is code:

 const [timeOut, setTimeOut] = useState('')

useEffect(() => {
    if (status !== 'unPaid') return;

    const timer = window.setInterval(() => {
      setTimeOut(formatTime(createdAt));
    }, 1000);

    return () => window.clearInterval(timer);
  }, [createdAt, status]);



 const formatTime = (time) => {
    const timer = new Date(time).getTime() + 9000;
    const currentTime = new Date().getTime();
    const distance = timer - currentTime;


    let min = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    let sec = Math.floor((distance % (1000 * 60)) / 1000);
    let res = Math.abs(min) + ':' + Math.abs(sec).toString().padStart(2, '0');
    console.log(res)
    return res;
  };


  // DELETE RESERVATION
  const deleteReservation = async (id) => {
    
    try {
      const config = {
      headers: {
        "Content-Type": "application/json",
      },
    };      

    const res = await axios.post('/api/booking/deleteReservation', {id}, config)
    console.log(res.data)

    } catch (error) {
      console.log(error.message)
    }

  }

  // UPDATE DATA
   if(timeOut === '0:01'){
      deleteReservation(_id)  
      getDetails()
  
  } 

 return (
   ...
  <td>{status === 'unPaid' ? 'Pay ' + `${timeOut}` : 'Paid'}</td>


Peret
  • 79
  • 8
  • 5
    Remember that you are using client-side programming, which means that all useEffect, hooks and functions will only work while your application page is open. That's why the timeout works for you, because the page is open and running. If you need a process that performs the deletion after some time, you will need to find a way to have a backend or server-side service that handles those required situations. – KrLiTs Jul 26 '23 at 20:39
  • Thank you, I fixed it in backend. I didn't think about it that way. I am a bit wiser :) – Peret Jul 27 '23 at 15:23

0 Answers0