Array with only one updated output using react

146 Views Asked by At

I am developing a MERN app where I have members with their time and date slot, the time slot is an array which could be more than one slot for one staff or member, so whenever the user clicks on the date picker after clicking on a specific staff, the user should get time slot of this slot depending on what is in their slot, the problem that I am facing is if a staff has more than one busy slot for example (two slots), which becomes an array of objects, the time slot render twice and each one updates seperatly depending on the data. Here is the code:

So first I get the data from an array and pass it to a function:

{members.timeSlot.map((slot, is) =>
    <div key={is} >
       {counter(slot.slot_date ,slot.slot_start_time, slot.slot_end_time)}
    </div>
)}

The function above it:

 let counter = (storedDate, startTime, endTime) => {

        var times = ['09:00 AM', '10:00 AM', '11:00 AM', '12:00 PM','01:00 PM', '02:00 PM', '03:00 PM', '04:00 PM', '05:00 PM', '06:00 PM'];
        var rows = [];
      

           var sDate = new Date(storedDate); 
           let storedDay = sDate.getDate();
           let storedMonth = (sDate.getMonth() + 1 );
           let storedYear = sDate.getFullYear();

           let selectedDate = date  
           let selectedDay = selectedDate.getDate(); // 11
           let selectedMonth = (selectedDate.getMonth() + 1);
           let selectedYear =  selectedDate.getFullYear();
        
        for (var j = 0; j < times.length; j++) {
            let count = j + 9;
            if(storedDay === selectedDay && storedMonth === selectedMonth ) {

            if(count >= startTime && count <= endTime ) {
                 continue;
            } else {
                rows.push(
                    <>
                         <label style={{backgroundColor:'pink', color:'blue'}}><input type="radio" value={count} key={j} style={{position:'relative'}} name="schedule-weekly-option" onClick={()=> setTimes(count)} />&nbsp;{times[j]} &nbsp;</label>
                    </>
                  );
               }
        } else  {
                rows.push(
                <>
                     <label style={{backgroundColor:'blue', color:'pink'}} ><input type="radio" value={count} key={j} style={{position:'relative'}} name="schedule-weekly-option" onClick={()=> setTimes(count)} />&nbsp;{times[j]} &nbsp;</label>
                </>
              );
        }
        } return <div >{rows}</div>;
       
    }

so the output shows twice because there are two slots in the database like this

enter image description here

Should I update the array? and which is the best way to do it? I am using react hooks.

I would appreciate your help!

Thanks.

0

There are 0 best solutions below