Home > OS >  React: How to loop through object?
React: How to loop through object?

Time:04-18

enter image description here

patient.users returns enter image description here

patients.users it's an array of objects but I cannot loop through it. When I was trying to call patients.users[0] it returned "TypeError: Cannot read properties of undefined (reading '0')". Why is that?

function DoctorPanel() {
const location = useLocation();
const { id } = location.state;
const [patients, setPatiens] = useState('');

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

const getPatients = () => {
  api.getDoctorById(id).then(response => {
    setPatiens(response.data)
})

 }

console.log(patients.users)



return (

<div>
    <div className="container">
      <h2 className="text-center">List of Patients</h2>
      <table className="table table-bordered table-striped">
          <thead>
              <th>Employee First Name</th>
              <th>Employee Last Name</th>
              <th>Number</th>
          </thead>
          <tbody>
            {
              patients.users.map(patient => 
                      <tr>
                          <td>{patient.firstName}</td>
                           <td>{patient.secondName}</td>
                           <td>{patient.number}</td>
                      </tr>
               )
            }
          </tbody>
      </table>    
  </div>
</div>

) }

for loop, forEach, and with Object.keys don't work as well. How I can loop through it and display the details?

CodePudding user response:

The problem is because there is nothing in the patients.users array when you first render this component, so it says cannot read properties of undefined which is your array.

You then get the data in the useEffect which is run after the first render.

What you need to do is anywhere you access patients.users change to either:

patient?.users or patient && patient.users, this includes your console.log. What this does is check that patient array is not undefined before trying to access users on it.

EDIT:

Its also best practice in a useEffect to put the code in there rather than calling a function which exists outside. And you have a typo in the state setter setPatiens should be setPatients.

  • Related