Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use includes function on JSON array

I can’t seem to pass the conditional rendering no matter what value I pass into the includes function. The array freeSlotsList has values:

0: {id: 1, name: ‘MON1’, booked: 0, bookedBy: ”}

1: {id: 2, name: ‘MON2’, booked: 0, bookedBy: ”}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2: {id: 3, name: ‘MON3’, booked: 0, bookedBy: ”}

3: {id: 4, name: ‘MON4’, booked: 0, bookedBy: ”}

The following code never enters the if statement:

    const renderTableData = () => {
    let id = 1;
    const activeButton = () => {};
   
   
    return (
      <tr>
        {days.map((val) => (
          <td>
            {timeSlot.map((n, i) => {
            console.log(freeSlotsList)
              if (freeSlotsList.includes(1) == true) {
                return <h1>Testing</h1>;
              }

              return (
                <button id={id++} className={activeButton}>
                  {n}
                </button>
              );
            })}
          </td>
        ))}
      </tr>
    );
  };

The declaration of the useState:

   const [freeSlotsList, setFreeSlotsList] = useState([]);
  console.log(freeSlotsList);
  useEffect(() => {

    Axios.post("http://localhost:3001/api/get/week1/ex").then((response) => {
      setFreeSlotsList(response.data);
    });
  }, []);

EDIT:

it should say:

 if (freeSlotsList.includes(id) == true) {
                return <h1>Testing</h1>;
              }

>Solution :

the condition will never be true since the array has only objects. I bet you want to find if some of the objects has the id === 1. In that case you can use find or some.

freeSlotsList.some(slot => slot.id === id)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading