Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set JSON array to state in React?

I have this bellow App.js code:

import React, { Component } from 'react';
import axios from 'axios'


class Axios extends Component {

    constructor() {
        super();
        this.state = {
            item : '',
        }
    }

    componentDidMount() {
        axios.get('https://restcountries.com/v3.1/capital/lima')
        .then( response => {
            const data = response.data.map(( data )=>{
                this.setState({
                    item : data
                });
            });
        })
        .catch( error => {
            alert( error );
        });
    }

    prepare() {
        console.log( this.state.item );
    }

    render() {
        return (
            <div>{this.prepare()}</div>
        )
    }
}

export default Axios;

My goal is to get the common name from this API: https://restcountries.com/v3.1/capital/lima

Now on componentDidMount() method, I need to set the API return data to the item state so that I can loop through using the prepare method.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But I don’t have any idea how to set the API return array JSON data to the item state?

>Solution :

Update your state.item to a blank array.

constructor() {
    super();
    this.state = {
        item : [],
    }
}

In componentDidMount(), update the code to accept response :

 componentDidMount() {
    axios.get('https://restcountries.com/v3.1/capital/lima')
    .then( response => {
        this.setState({
                item : response.data
            });
    })
    .catch( error => {
        alert( error );
    });
}

In render(), you can use map on state.item and can loop on it.

render() {
    return (
        <div>{this.state.item.map(data,index)=>(
              //some UI mapping to each `data` in `item` array
        )}</div>
    )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading