import { useEffect,useState } from "react";
export default function NasaApi(){
const[mars,setMars]=useState();
useEffect(()=>{
fetch('https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&api_key=DEMO_KEY')
.then(response=>response.json())
.then(data=>{
setMars(data)
})
},[])
return(
<div className="container-fluid">
<h2>Mars Photos</h2>
<table className="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>Camer_full_name</th>
<th>rover name</th>
<th>preview</th>
</tr>
</thead>
<tbody>
{
mars.photos.map(photo=><tr>
<td>{photo.id}</td>
</tr>)
}
</tbody>
</table>
</div>
)
}
i am get getting runtime error
Cannot read properties of undefined (reading ‘photos’)
TypeError: Cannot read properties of undefined (reading ‘photos’)
2
Answers
As your state does not have a default value, when your page first renders it will attempt to map a property of an undefined value.
In order to ensure that it has something to map before the response from the API is obtained, you should either check if object exists or provide a default value.
Checking if object exists
Providing default value