I want to load planet data from an API using React and put this data into a Material UI card component. Unfortunately the planet API I'm using doesn't have photographs, which I want to also display in the card. For this, I'm using another API.
API for fetching planet data: https://api.le-systeme-solaire.net/rest
API for fetching planet images: https://images-api.nasa.gov/search
I have figured out how to render each planet component with its respective info into a card, but don't know how to map each NASA image to the respective planet:
This is the code for the App.js component:
import React, {useState, useEffect} from 'react';
import './App.css';
import axios from 'axios'
import Block from "./Block"
function App() {
const [planets, setPlanets] = useState([])
const [images, setImages] =useState([])
const getPlanets = async()=>{
const data = await fetch
('https://api.le-systeme-solaire.net/rest/bodies') //Await for first fetch promise to resolve
const planets = await(data.json()) //Await for data.json to resolve and save this planets
setPlanets(planets.bodies.filter
(planet =>planet.isPlanet && planet.name.indexOf('1')===-1))
}
const getImages = (name)=>{
axios.get('https://images-api.nasa.gov/search',{
params:{
q: name
}
})
.then(res =>
setImages(images.concat(res.data.collection.items[0].links[0].href)))
}
console.log(planets)
useEffect(()=>{
getPlanets();
},[])
useEffect(()=>{
if(planets){
planets.map(planet =>getImages(planet.englishName))
}
},[])
console.log(images)
console.log(planets.length)
return (
<div className="App">
{planets.map(planet =>
(<Block
key = {planet.id}
id = {planet.id}
name = {planet.englishName}
dateDiscovered = {planet.discoveryDate}
mass = {planet.mass.massValue}
massExp = {planet.mass.massExponent}
image = ???
/>)
)}
</div>
);
}
export default App;
The code for Block.js is as follows:
import React, {useState, useEffect} from 'react'
import './Block.css'
import {Card, CardContent} from '@material-ui/core'
function Block(props){
return (
<div>
<Card>
<CardContent>
<div className = "planetInfo">
<h4>{props.name}</h4>
<h5>Mass: {props.mass}*10^{props.massExp} kg</h5>
<h5>Discovery Date: {props.dateDiscovered}</h5>
<h5>ID: {props.id}</h5>
<img src = {props.image}/>
</div>
</CardContent>
</Card>
</div>
)
}
export default Block
I have a feeling my structure isn't right. Any help would be appreciated.