I have a problem making a request to the StarWars API

Viewed 21

I am a person who is learning to use APIs with react and i have a problem because my code does not work. I get the following error in the console: Uncaught TypeError: Cannot read properties of undefined (reading 'map') App.jsx:24 .However I have optional chaining applied. I show you my code and I hope you can help me

useFetch.js

import axios from "axios"
import { useEffect, useState } from "react"

const useFetch = url => {

    const [response, setResponse] = useState()

    useEffect( () => {
        axios.get(url)
        .then(res=>setResponse(res.data))
        .catch(err=> console.log(err.message))
    }, [])

    return response

}

export default useFetch

App.jsx

import axios from 'axios'
import { useEffect, useState } from 'react'
import './App.css'
import FormInput from './components/FormInput'
import Residents from './components/Residents'

function App() {

  const [planets, setPlanets] = useState()
  const [response, setResponse] = useState()

  const number = parseInt(response)

  const updatePage = number => {
    const URL = `https://swapi.dev/api/planets/${number}/`
    axios.get(URL)
      .then(res => setPlanets(res.data))
      .catch(err => console.log(err.message))
  }

  useEffect(() => {
    const URL = `https://swapi.dev/api/planets/${number}/`
    axios.get(URL)
      .then(res => updatePage())
      .catch(err => console.log(err.message))
  }, [])

  console.log(number)

  return (
    <div className="App">
      <FormInput
        setResponse={setResponse}
      />
      <hr />
      {
        planets?.residents.map(resident => (
          <Residents
            resident={resident}
            key={resident.name}

          />
        ))
      }
    </div>
  )
}

export default App


Residents.jsx

import React from 'react'
import useFetch from '../hooks/useFetch'

const Residents = ({ resident }) => {

          const users = useFetch(resident)


          console.log(users)
   
  return (
    <article>
        

    </article>
  )
}

export default Residents
1 Answers

It's because your residents is not an array. Make it array first or something you are storing in resident is not a object and map() method only works on array not on object. So fix it.

planets?.residents?.map()

use "?" after residents and your residents is not an array. So you need to make it array or whatever you are storing in you residents variable is not an array please cross check you variable/state.

Related