Home > Net >  IF/ELSE condition not working properly and Rerendring duplicates React
IF/ELSE condition not working properly and Rerendring duplicates React

Time:03-26

My goal here is to check a checkin and checkout date and see if a room is available or not

if availdata[p.roomId][date].i==0 then the room at that range of dates is not available so it will be displayed as not available

if not it will check its price with availdata[p.roomId][date].p1 and display it with a price instead

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])

                    setIsLoading(true);


                }

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

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

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

    {data.map(p=> {

    if (isLoading && isLoading2){

        for (var day = strToDatein; day <= strToDateout; day.setDate(day.getDate()   1)) {
            

            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;
                prices.length=0;
                console.log("room:" p.roomId "available?" availdata[p.roomId][date].i)

                HC.push(<div key={p.roomId}>
                    <HotelCards
                        idroom={p.roomId}
                        title={p.roomName.toUpperCase()}
                        status={true}
                        price={prices}
                        img={p.pictures[0].url}
                        avail={notavailableat}
                        rows={rowss}
                        guest={selectedGuest}
                    /></div>)
                break;
            }
            else
            {
                rowss.length=0;
                prices.push(availdata[p.roomId][date].p1);
                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={prices}
                    img={p.pictures[0].url}
                    avail={notavailableat}
                    rows={rowss}
                    guest={selectedGuest}
                /></div>)



            }

        }
    }

    })

    return (
        <div className={`${styles.containers}`}>

            {HC}

        </div>
    );

}}





in my case it's displaying each room 4 times with same price image

CodePudding user response:

Since HC is an extra component, every time UseEffect is called all its children will be updated. Since you set

price={prices}

in your attributes, every update would make every child have the same price value.

Instead, you can just directly read from your availdata array

price={availdata[p.roomId][date].p1}

CodePudding user response:

    if (isLoading && isLoading2 && availdata[p.roomId]){


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


            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;
            
                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]);
                    }

                }

                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>)



            }
            }

    }

    })

for this i decided to only show the available rooms , until i get a better suggestion.

  • Related