Answer the question
In order to leave comments, you need to log in
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>
);
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question