Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

338
Vistas
Render a nested object from API - Type Error: Cannot read properties of undefined

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
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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>  
)
about 4 years ago · Juan Pablo Isaza Denunciar

0

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>
    )
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda