Home > Blockchain >  Able to log array in console, but can't loop through it
Able to log array in console, but can't loop through it

Time:03-12

Running into a problem. In react I'm grabbing data from a json api. Everything worked fine until I tried to display it. Except, I'm able to log it on the console.

What the console logs:

pic

<ul role="list" className="divide-y divide-gray-200 dark:divide-gray-700">
{username !== "null" && leaderlist.length > 2 && console.log(leaderlist) && leaderlist.map((leader, index) =>
       <li className="py-3 sm:py-4 text-white">
           Log 
        </li>
      )}
     <li className="py-3 sm:py-4 text-white">
         list length {leaderlist.length} 
     </li>
   </ul>

What it displays:

enter image description here

The code that sets

const [leaderlist, setleaderlist] = React.useState([]);
fetch(`${baseurl}/allusers`)
     .then(res => res.json())
     .then(data => {setleaderlist(data); console.log(data)})
     .catch(err => console.log(err));

CodePudding user response:

username !== "null" && leaderlist.length > 2 && console.log(leaderlist) && leaderlist.map((leader, index)

console.log(leaderlist) does not have a return value and thus leaderlist.map((leader, index) ...) does not run since you're using &&. You need to remove the console.log statement or use ; instead of &&.

  • Related