A
A
Alexey Yakovlev2020-10-19 19:24:01
JavaScript
Alexey Yakovlev, 2020-10-19 19:24:01

How to get normal data from json?

I process the link using fetch (I work on React):

const InfoApi = () => {
    fetch(`https://api.covid19api.com/summary`)
        .then(async(data) => {
            const dataJson = await data.json();
            console.log(dataJson)

            for (let item in dataJson) {
                if (dataJson.hasOwnProperty(item)) {
                    console.log(item);
                }
            }
        })
        .catch(e => {
            console.log(e);
        })

    return (
        <div className="infoApi"></div>
    );
}


I get data like this:
Message, Global, Countries, Date

Although Global is an object, Countries is an array, I want to process Countries, but I can't, because Countries is a string
like everything I got (Message, Global, Countries, Date) . How to get normal data?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
iamsergo, 2020-10-20
@iamsergo

If you rewrote the component the way it is written in reality, then this approach is wrong.
Asynchronous code, in principle, all code with side effects, is taken out to special places.
If you need to get data when loading a component, the component lifecycle methods are used:
If you are using a class component, then in the componentDidMount()
method If it is functional , then in useEffect()
If you need to get them on an event (click, etc.), then into a function, then call this function in the event handler, or do everything in the handler right away.
Also, your request code is not entirely clear.
fetch returns a promise with response. The response(server response object) has a special json() method that returns the body of the response from the server in the appropriate format.
After receiving the data, they must be saved in order to be used when rendering. Can be saved to state.
Classwise
In the constructor : this.state = { countries : [] }
this.setState({ countries : data.Countries })
Functional
At the beginning of the component, before the request : const [countries, setCountries] = useState([])
setCountries(data. Countries)
I would write as follows for the data that is needed when loading the component:

const InfoApi = () => {
  useEffect(() => {
    fetch(`https://api.covid19api.com/summary`)
    .then(res => res.json())
    .then(data => {
        console.log(data)
        // работа с data, в data будет все как надо: Countries - объект
       setCountries(data.Countries)
    })
  }, [])

  return(
     <div className="infoApi">
      {countries.map(country => <div>{country.Country}</div>)}
     </div>
  )
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question