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
You are using coin properties before they have data from your api, as the initial value is an empty object {}
you should validate if the data exists or it will raise the error:
useEffect(() => {
const getData = async() ={
await axios.get(url).then((res) => {
setCoin(res.data)
}).catch((err) => {
console.log(err)
})
}
getData()
}, [])
...
return (
<div>
<h1>**{coin.name ? coin.name : ''}**</h1>
<p>**{coin.market_cap ? coin.market_cap.usd : ''}**</p> ------>> Error here
</div>
</div>
)
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>
)