React - State Hook map is not a function

by tramada   Last Updated July 12, 2019 05:26 AM

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 })
            console.log('estado\n')
            console.log(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 = 'https://swapi.co/api/planets'

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:

enter image description here

Tags : reactjs


Related Questions


Updated November 07, 2018 13:26 PM

Updated June 21, 2015 23:11 PM

Updated October 20, 2018 07:26 AM

Updated August 07, 2017 01:26 AM