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