1

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>
}

}

2 Answers 2

1

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>
        )}
)}
Sign up to request clarification or add additional context in comments.

4 Comments

Please let me know if it solved your problem or not.
I'm fresh on React so im currently trying to implement this to my project. I'm getting this problem: × TypeError: Cannot read property 'map' of undefined, I'm guessing im not doing it right.
I made it work, where can i read more about this? So that i actually understand whats going on behind the scenes? Thanks for you help :)
Well, in my opinion, the documentation of react is the best resource as they have written it very informative and simple. I also found videos of Mosh on youtube (youtube.com/watch?v=Ke90Tje7VS0) useful and simple when I started learning about it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.