Getting Error when trying to acess JSON value can you help me?

Hi guys, I’m trying to get some data from a API, its a JSON object but I’m getting the following error
TypeError: this.state.confirmado[2] is undefined when I try to get the value from this JSON

{
  "provinceState": "Parana",
  "countryRegion": "Brazil",
  "lastUpdate": 1623932546000,
  "lat": -25.2521,
  "long": -52.0215,
  "confirmed": 1162966,
  "recovered": 805154,
  "deaths": 28847,
  "active": 328965,
  "admin2": null,
  "fips": null,
  "combinedKey": "Parana, Brazil",
  "incidentRate": 10171.1594682401,
  "peopleTested": null,
  "peopleHospitalized": null,
  "uid": 7616,
  "iso3": "BRA"
}

let’s say if I console.log(this.state.confirmado[2]) I have acess to the Object, but if I try to have acess to the value
of the object lets say

console.log(this.state.confirmado[2].confirmed) I get the message this.state.confirmado[2] is undefined

This is my code

class App extends React.Component {
  
  constructor(props) {
    super(props)
    this.state = {
      dados: '',
      confirmado:[] ,
      recuperados:'',
      mortes:'',
      isLoading: true
    }; 
  }

  componentDidMount() {
    Promise.all([
      fetch(covidBrasil).then(res => res.json())
      .then(resultado =>
        this.setState({
          dados: resultado,
          isLoading: false
        })),
        fetch(covidConfirmed).then(res => res.json()).then(resultado =>
          this.setState({
            confirmado: resultado
          })),
          fetch(covidRecoverd).then(res => res.json()).then(resultado =>
            this.setState({
              recuperados: resultado
            })),
            fetch(covidDeaths).then(res => res.json()).then(resultado =>
              this.setState({
                mortes: resultado
              })),
    ])
   
  }

  render() {
     
    let isCarregando = this.state.isLoading

    if (isCarregando === false) {
     
     
        console.log(this.state.confirmado[2])
      
    
     
      return (
        <div>
          <Box className="br-Status">
          <div className="box-topo">
              <h2 className="br-conf"> Casos Confirmados:</h2>
        
              <p className="desc-value">{this.state.dados.confirmed.value}</p>

              <h2 className="br-conf">Caso Recuperados:</h2>

              <p className="desc-value">{this.state.dados.recovered.value}:</p>

              <h2 className="br-conf">Caso Mortes:</h2>

              <p className="desc-value">{this.state.dados.deaths.value}</p>
            
              </div>
          </Box>

       
          <div className="box-sul">
              <h2 className="br-conf"> Casos Confirmados:</h2>
        
              <p className="desc-value"></p>

              <h2 className="br-conf">Caso Recuperados:</h2>

              <p className="desc-value">:</p>

              <h2 className="br-conf">Caso Mortes:</h2>

              <p className="desc-value"></p>
            
              </div>
      
        </div>

      )

    }
    return (
      <div>
        <h1>Olá</h1>
      </div>
    )
  }

}

export default App;

So how does confirmado look?
You show a JSON, which doesn’t really help. Or is this JSON saved in confirmado[2] ?
If so, dot-notation assumes a value is bound to a variable by that name. However in JSON, the keys are strings, not variables. Hence you access them via ["confirmed"] and not .confirmed

this.state.confirmado[2] is undefined seems to suggest you are not getting the object, so you can’t get the property value either.

Are you not just trying to access the data before you have actually gotten it back from the API? As far as I can tell, isLoading being false doesn’t mean you got the data back from all the fetch calls.

It’s for the same reason that you really should check the data before trying to render it (using optional chaining, or &&, or a ternary, etc.).

Example
import * as React from "react";

export default class getData extends React.Component {
  state = {
    data: null
  };

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => res.json())
      .then((json) => this.setState({ data: json }));
  }
  render() {
    console.log("state: ", this.state.data); // state: null // state: API data
    return (
      <div>
        {this.state?.data?.map(({ id, name }) => (
          <p key={id}>{name}</p>
        ))}
      </div>
    );
  }
}
1 Like

hi I this is where confirmado is getting the data from https://covid19.mathdro.id/api/countries/BR/confirmed

i tried to use [‘confirmed’] I still get the error

It’s an object, if the property exists you can dot on to it using the property name.

Edit: using the API instead

const getData = async () => {
  const res = await fetch('https://covid19.mathdro.id/api/countries/BR/confirmed');
  const json = await res.json();
  console.log(json[2].confirmed)
}

getData()

Move the console.log inside the fetch/.then see if you can access it there. Because as it is now, you are trying to log the data before you have access to it (as far as I can tell).

1 Like

Thank you, it worked

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.