PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] How to use includes function on JSON array

 October 14, 2022     axios, reactjs     No comments   

Issue

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: ''}

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)


Answered By - Toni Bardina Comas
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,205,448

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing