How to get normal data from json?

  • 0
    I am fetching the link (working in React):
    const InfoApi = () => {
            .then(async(data) => {
                const dataJson = await data.json();
                for (let item in dataJson) {
                    if (dataJson.hasOwnProperty(item)) {
            .catch(e => {
        return (
            <div className="infoApi"></div>

    I get the following data:
    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 do I get normal data?
    JavaScript Anonymous, Mar 31, 2019

  • 1 Answers
  • 0
    If you rewrote the component the way it is actually written, then this approach is wrong.

    Asynchronous code, in principle all code with side effects, is placed in special places.

    If you need to get data when loading a component, use the component lifecycle methods:

    If you are using a class component, then in the componentDidMount () method

    If functional , then in useEffect ()

    If you need to get them on event (click, etc.), then into a function, then call this function in the event handler, or do everything right in the handler.

    Also your request code is not clear.

    fetch returns a promise with response. Response (a response object from the server) has a special json () method that returns the response body from the server in the appropriate format.

    After receiving the data, you need to save it in order to use it for rendering. Can be saved in state.


    In the constructor: this.state = {countries: []}

    this.setState ({countries: data.Countries})


    At the beginning of the component, before the request: const [countries, setCountries] = useState ([])

    setCountries (data.Countries)

    I would write like this for the data that is needed when loading the component:

    const InfoApi = () => {
    useEffect(() => {
    .then(res => res.json())
    .then(data => {
    // работа с data, в data будет все как надо: Countries - объект
    }, [])

    <div className="infoApi">
    { => <div>{country.Country}</div>)}

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!