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
Default value of your coin is empty object and since fetching data is async action when component tries to render for the first time it doesn't know about market_cap value so you need to add check for that prop when rendering.
This would solve your problem:
return (
<div>
{coin.name ? <h1>coin.name</h1> : null}
{
coin.market_data?.market_cap
? <p>{coin.market_data.market_cap.usd}</p>
: null
}
</div>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With