Im trying to figure out how to handle different API responses and map over them. So i can present them in my application.
Handeling the getArrayofObjects function is no problem at all. However, the Nasa API contains object structure with nested objects within.
{
element_count: 25,
links: {
next: https:link1.com,
prev: https:linkprev.com,
self: https:linkself.com }
},
near_earth_objects: {
2015-09-08: [{absolute_magnitude_h: 19.3,
close_approach_data: [{close_approachdate: 2015:01:12}]},
estimated-diameter: {}, id: 132342323, links: {}]
i want to map over this object however react gives me the error mentioned in the title. How can i map over this data and allow it to be presented orderly in the application?
I have the following component:
import styles from '../styles/Home.module.css'
const axios = require('axios')
import { useState } from 'react'
export default function Home() {
const [nasa, setNasa] = useState([])
const [posts, setPosts] = useState([])
const returnNestedObjects = () => {
axios
.get(
'https://api.nasa.gov/neo/rest/v1/feed?start_date=2015-09-07&end_date=2015-09-08&api_key=hqIAqlEjXdGOE4K0H44Oj0Bq20tID1ytS3IdYuT4'
) // goed kijken naar de API of het de juiste data heeft als format
.then((response) => {
setNasa(response.data)
console.log('Objects of nested NASA objects', response.data) // returs object with nested objects // TODO uitvogelen hoe je deze mapped
})
.catch((error) => {
setIsError(true)
console.log(error)
})
}
const results = Object.keys(nasa).map((key) => {
console.log(key) // ️ name, element_count, near_earth_objects, links console logt the key
console.log(nasa[key]) // ️ {next: somelink.com/} 25, {2015-09-08} console logt the value
return { [key]: nasa[key] } // returns key + value
})
console.log('results', results)
const stringifyObjects = JSON.stringify(results)
const getArrayofObjects = () => {
axios
.get('https://jsonplaceholder.typicode.com/posts') // returns Array
.then((response) => {
setPosts(response.data)
console.log('Array Of objects', response.data) // returs Array with nested objects => .map to map over them
})
.catch((error) => {
setIsError(true)
console.log(error)
})
}
return (
<div className={styles.container}>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to{' '}
<span className={styles.headerTitle}>
<h2>Testing API API</h2>
</span>
</h1>
<div className={styles.buttoncontainer}>
<button onClick={returnNestedObjects}>Nested Objects</button>
<button onClick={getArrayofObjects}>Array of Objects</button>
</div>
<ul>
{posts.map((item) => (
<li>{item.title}</li>
))}
</ul>
<ul>
{results ? (
<ul>
<li>NASA API RESULTS: {results}</li>
</ul>
) : (
<p>Loading...</p>
)}
</ul>
</main>
</div>
)
}