Niqqo
Niqqo

Reputation: 41

Loop through json object and display the data with React?

The api response i get back has 10 objects of people inside it and i would like react to display the Persons name and gender. I'm not sure how to accomplish this. Is states even the right way to go about this or should i try to save my response inside of an array only?

Any help is appreciated.

state = {
        Person: null,
        Gender: null      
}
    
async componentDidMount() {
    const url = "**********************************************";
    const response = await fetch(url);
    const data = await response.json();
    this.setState({Person: data[0].Name})
    this.setState({Gender: data[0].Gender})

    }

render() {
    return  <div>
        <p>
        {this.state.Person}
        </p>

        <p>
        {this.state.Gender}
        </p>
}

}

Upvotes: 1

Views: 51

Answers (2)

alisasani
alisasani

Reputation: 2968

Yes, you should store your data in state and map it to display the name and gender of each person.

async componentDidMount() {
    const url = "**********************************************";
    const response = await fetch(url);
    const data = await response.json();
    this.setState({ data })

    }

render() {
    return(
        {this.state.data.map((el, id)=> 
        <div>
        <p>Name:{el.Name}</p>
        <p>Gender:{el.Gender}</p>
        </div>
        )}
)}

Upvotes: 1

Pete
Pete

Reputation: 1

Should definitely use an array of "Persons", also try using hooks :)

Upvotes: 0

Related Questions