This is my first react app and it was for a job interview challenge. The app is really simple and it works, but although I don't think I'm gonna get it, could I have some feedback about what is wrong and how could I improve it?
***I already submitted this, so is not cheating, I just need to know how can I be better
- The way requests are being made is correct?
- Should planetas object be populated this way? Is there a better approach? (thats how I managed to make it work)
- planetas.films was taking too long to be loaded and giving me a map is undefined problem, is my conditional render bad?
- And anything else you find to be wrong
service:
import axios from 'axios'
const PLANETS_URL = 'https://swapi.co/api/planets'
const FILMS_URL = 'https://swapi.co/api/films'
const GetPlanets = async () => {
let planetas = {}
await axios.get(`${PLANETS_URL}`)
.then((p) => {
planetas = p.data.results
return axios.get(`${FILMS_URL}`)
}).then((f) => {
planetas.forEach((pv, i) => {
pv.films.forEach((pf, j) => {
f.data.results.forEach((el, k) => {
if(pf === el.url){
pv.films[j] = el
}
})
})
})
})
.catch((e) => {
console.error(e);
})
return planetas
}
export default GetPlanets
component:
import React, { useState, useEffect } from 'react'
import GetPlanets from '../services'
import { Loader, Container, Name, Info, Button } from '../components'
export default function Planetas () {
const [ counter, setCounter ] = useState(1)
const [ planetas, setPlanetas ] = useState([])
const [ toShow, setToShow ] = useState({})
useEffect( () => {
const fetchPlanetas = async () => {
const planetas = await GetPlanets()
setPlanetas(planetas)
setToShow(planetas[0])
};
fetchPlanetas()
}, [])
const handleClick = () => {
if(counter === (planetas.length - 1)){
setCounter(0)
setToShow(planetas[counter])
} else {
setCounter(counter + 1)
setToShow(planetas[counter])
}
}
if(typeof toShow.films !== 'undefined') {
return (
<Container>
<Name>{toShow.name}</Name>
<Info>
<p>Population: {toShow.population}</p>
<p>Climate: {toShow.climate}</p>
<p>Terrain: {toShow.terrain}</p>
Featured in Films:
<ul>
{toShow.films.map((film, key) => (
<li key={key}>{film.title}</li>
))}
</ul>
</Info>
<Button onClick={handleClick}>Next</Button>
</Container>
)
} else {
return(
<Loader>Loading...</Loader>
)
}
}