I know there are similar questions, but I can't find out why the error happens. Div shows, but then app crashes (as if was some length problem)
Code is similar to examples I found, like this sandbox
What am I doing wrong?
this is component:
import React, { useState, useEffect } from 'react'
/* import Button from '../Button' */
import { getPlanets } from '../../services/index'
import './Planetas.css'
const Planetas = () => {
const [planetas, setPlanetas] = useState([]);
useEffect(() => {
const fetchPlanetas = async () => {
const planetas = await getPlanets()
setPlanetas({ planetas })
};
fetchPlanetas()
}, []);
return (
<div className="planetas">
{
planetas.map((planeta, key) => {
return <div key={key}>{planeta.name}</div>
})
}
</div>
)
}
export default Planetas
this is api service:
import axios from 'axios'
const BASE_URL = '
export const getPlanets = async() => {
const planets = await axios.get(`${BASE_URL}`).catch((e) => {
console.error(e);
})
console.log('resp\n')
console.log(planets.data.results)
return planets.data.results
}
error:
4 Answers
setPlanetas({ planetas }) in this line you're setting your state to be an object with a planetas property, instead you need to do setPlanetas(planetas)
you have planetas state which is array data types but when you update planetas state you updated state with curly braces outside response array i.e setPlanetas({ planetas }) instead of setPlanetas(planetas).
useEffect(() => {
const fetchPlanetas = async () => {
const planetas = await getPlanets()
setPlanetas(planetas) // remove curly braces here
};
fetchPlanetas()
}, []);
I had a similar problem and I used:
Object.values(array).map()
It worked for me. I hope help somebody else.
Need an array here to map. => setPlanetas(planetas).