I am trying to retrieve data with map() method from this api. https://api.nasa.gov/DONKI/CME?startDate=yyyy-MM-dd&endDate=yyyy-MM-dd&api_key=DEMO_KEY
I am able to retrieve data from the first array but there’s antoher array inside the main array where I get the react error when trying to retrieve with another loop. The data needs to be retreived have been hilighted in the image…
import React from 'react'
import { useState, useEffect } from 'react'
import axios from 'axios';
const AstronomyPic = () => {
const [images, setImages] = useState([])
useEffect(() => {
axios.get('https://api.nasa.gov/DONKI/CME?startDate=yyyy-MM-dd&endDate=yyyy-MM-dd&api_key=DEMO_KEY')
.then(response => setImages (response.data)).
catch(error =>console.error(" Error fetchin users", error));
}, []);
return (
<div>
<h1 className="text-center mt-5">Astronomy</h1>
<ol>
{images.map((image) => (
<div><li>
<p>{image.activityID}</p>
<p>{image.catalog}</p>
<p>{image.startTime}</p>
<p>{image.sourceLocation}</p>
<p>{image.activeRegionNum}</p>
<p>{image.link}</p>
<p>{image.note}</p>
<p>Items: {images.items.map((item) => (
<p>{item.instruments}</p>
))}</p>
</li>
</div>
))}
</ol>
</div>
)
}
export default AstronomyPic
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
2
Answers
Looks like some item does not have an
instruments
attribute. You might want to check before you loop through theinstruments
attribute.Seems to be instruments are not available in all elements. You can avoid any null reference exception using the optional chaining operator. Refer the code below :