Skip to content
Advertisement

date copy stops the loop statement to function as intended

What i am trying to do is to display available rooms which are in data i map the rooms using data.map , check if one is available between a given ( checkin and checkout date ) using availdata[p.roomId][date].i==0 , if not it will display the available room . the code works fine but as soon as it finds an available room it stops (which means it stops at the else statement ) and won’t look for the rest of the rooms . Any suggestions ? using break ; doesn’t have anything to do with the problem i am facing .

import React,{useState,useEffect} from 'react';
import HotelCards from './HotelCards';
import styles from '../styles/Options/Options.module.css';
import {Checkkout as checkkout}  from "./Hero";
import {Checkkin as checkkin}  from "./Hero";

import {format} from "date-fns";
let HC=[];
let prices =[];
let notavailableat="";
let rowss=[];
export default function Options({selectedGuest}) {
    const [availdata, setavailData] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [isLoading2, setIsLoading2] = useState(false);
    const [data, setData] = useState([]);

    // request Headers
    const requestOptions = {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },

    };
    const requestOptions2 = {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },

    };


    //Get the rooms info along with the ID
    const fetchData = () => {
        fetch('http://localhost:3001/api/rooms', requestOptions)
            .then(response => response.json())

            .then((result) =>{
                    console.log("roooms"+result)
                    setData(result.rooms)
                    setIsLoading2(true);

                }

            )
            .catch((err) => console.log("error"));
    };

    useEffect(() => {
        fetchData();
    }, []);

    //get the i and p variables
    function fetchData1() {
        fetch('http://localhost:3001/api/availability', requestOptions2)
            .then(response => response.json())

            .then((result) =>{
                    setavailData(result.availability[0])


                    console.log('ooooooooooh'+result.availability[0][7264])
                    setIsLoading(true);


                }

            )
            .catch((err) => console.log("error"));
    }

    useEffect(() => {
        fetchData1();
    }, []);

    prices.length=0;
    var strToDatein = new Date(checkkin)
    var strToDateout = new Date(checkkout)
    let trys = 0;

    data.map((p) =>{

    if (isLoading && isLoading2 ){


        for (var day = strToDatein; day < strToDateout; day.setDate(day.getDate() + 1)) {
            HC.length=0;

            console.log(day + "dekhel for");

            var diplaydate = format(day,"dd  MMM ");

            var date = format(day, 'yyyyMMdd');

            if (availdata[p.roomId][date].i==0){

                rowss.push(<p key={availdata[p.roomId][date]}> not available at {diplaydate} </p>);
                notavailableat="not available at "+diplaydate;
                console.log(+p.roomId+"not available at "+diplaydate)


                break;
            }
            else
            {console.log("dateeee"+ date);
                rowss.length=0;
                prices.length=0;
                prices.push(availdata[p.roomId][date].p1);
                var total_price = 0;
                if(prices.length!==0){
                    for (var i=0;i<=prices.length-1;i++){
                        total_price+=parseFloat(prices[i]);
                    }

                }
                console.log("room:"+p.roomId+"price?"+availdata[p.roomId][date].p1)

                HC.push(<div key={p.roomId}>
                <HotelCards
                    idroom={p.roomId}
                    title={p.roomName.toUpperCase()}
                    status={true}
                    price={total_price}
                    img={p.pictures[0].url}
                    avail={1111}
                    rows={rowss}
                    guest={selectedGuest}
                /></div>)



            }}


    }

    })


    return (
        <div className={`${styles.containers}`}>
            {HC}
        </div>
    );
}

Advertisement

Answer

The problem in your code is this assignment in the for loop:

var day = strToDatein;

Dates are objects and objects are not copied. The references are copied. day and strToDatein contain references to the same object. day.setDate(day.getDate() + 1) modifies strToDatein. After the first room was found, strToDatein < strToDateout returns false and the for loop is skipped for all other rooms.

You can fix your problem with a real copy of the Date object in the for loop:

const data = [{
  roomId: 0,
  roomName: '0'
}, {
  roomId: 1,
  roomName: '1'
}, {
  roomId: 2,
  roomName: '2'
}];
const isLoading = true;
const isLoading2 = true;
const strToDatein = new Date(2022, 0, 1);
const strToDateout = new Date(2022, 0, 3);
const HC = [];
const availdata = [{
  "20220101": {
    i: 0,
    p1: 100
  }
}, {
  "20220101": {
    i: 2,
    p1: 100
  },
  "20220102": {
    i: 2,
    p1: 100
  },
  "20220103": {
    i: 2,
    p1: 100
  }
}, {
  "20220101": {
    i: 0,
    p1: 100
  }
}];
const rowss = [];
const prices = [];

function format(date) {
  return `${date.getFullYear()}${`${date.getMonth()+1}`.padStart(2, 0)}${`${date.getDate()}`.padStart(2, 0)}`;
}

data.forEach((p) => {
  if (isLoading && isLoading2) {
    for (var day = new Date(strToDatein); day < strToDateout; day.setDate(day.getDate() + 1)) {
      console.log(day + "dekhel for");
      var diplaydate = format(day, "dd  MMM ");
      var date = format(day, 'yyyyMMdd');
      if (availdata[p.roomId][date].i == 0) {
        rowss.push(`<p key = {
                availdata[p.roomId][date]
              }> not available at {
                diplaydate
              }</p>`);
        notavailableat = "not available at " + diplaydate;
        console.log(+p.roomId + "not available at " + diplaydate)
        break;
      } else {
        console.log("dateeee" + date);
        rowss.length = 0;
        prices.length = 0;
        prices.push(availdata[p.roomId][date].p1);
        var total_price = 0;
        if (prices.length !== 0) {
          for (var i = 0; i <= prices.length - 1; i++) {
            total_price += parseFloat(prices[i]);
          }
        }
        console.log("room:" + p.roomId + "price?" + availdata[p.roomId][date].p1)
        HC.push(`<div key={${p.roomId}}>` +
                '<HotelCards' +
                ` idroom={${p.roomId}}` +
                ` title={${p.roomName.toUpperCase()}}` +
                ` status={true}` +
                ` price={${total_price}}` +
                ' img={p.pictures[0].url}' +
                ' avail={1111}' +
                ' rows={rowss}' +
                ' guest={selectedGuest}' +
                '/></div>');
      }
    }
  }
});

console.log(HC);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement