I'm trying to access information from this API. I can access the first level however when I try to access any property past the first level I get an error stating TypeError: Cannot read properties of undefined (reading 'usd').
I am using a functional component and the useEffect() hook to call my API in React.
JSON API example:
{
"name" : "Bitcoin",
"market_cap" : {
"usd" : 100
}
}
From what I understand this is because the API has not been completely fetched so the first level is coming back as undefined. I am able to access the first level (coin.name), but when I try (coin.market_cap.usd) I get the error.
Any suggestions?
const Coin = () => {
const params = useParams()
const [coin, setCoin] = useState({})
const url = `https://api.coingecko.com/api/v3/coins/${params.coinId}`
useEffect(() => {
axios.get(url).then((res) => {
setCoin(res.data)
}).catch((err) => {
console.log(err)
})
}, [])
return (
<div>
<h1>{coin.name}</h1>
<p>{coin.market_cap.usd}</p> ------>> Error here
</div>
</div>
)
}
export default Coin