Pat Mellon Pat Mellon - 1 month ago 15
Javascript Question

Accessing data from Axios GET request

I'm having trouble accessing data from an Axios GET request. I'd like to be able to iterate through all of the data I get and create a table that displays the username, avatar, and score for each user. The only way I'm able to currently render a single username is with the following code:

this.setState({name: res.data[0].username});


But the above code only gives me access to the first object in the URL I use in the GET request. If I use this code:

this.setState({name: JSON.stringify(res.data)});


I'm able to render the entire object as a string. So that makes me think I need to update my render method, but I'm not sure how.

What steps should I take so that I can map over the state that I'm setting and render each user's data in a table or list?

class LeaderBoard extends React.Component {

constructor(props) {
super(props)
this.state = {
name: []
}
}

componentDidMount(){

axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/recent').then(res =>
{

this.setState({name: res.data[0].username});
});

}


render () {

return (
<div>
<h1>{this.state.name}</h1>

</div>
)
}
}


ReactDOM.render(
<LeaderBoard/>, document.getElementById("app"));

Answer Source

You're on the right track, you're just missing a few key pieces.

Step 1: Add the entire array to your state

I'm not sure of the exact structure of your data, but you likely want to do this

componentDidMount(){

axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/recent').then(res => 
{

this.setState({data: res.data});
   }); 

}

Now you have all the data you want to work with in your state, ready to be iterated over.

Step 2: Use .map() to create the JSX elements you want

This code here:

render () {

return (
  <div>
    <h1>{this.state.name}</h1>
  </div>
  )
 } 
}

The big fault here is that it will only ever render one thing, because, well, that's all there is. What you want to do is .map() through and create a bunch of names from your data, right?

That would look more like this.

  render () {
   const namesToRender = this.state.data.map(val => {
     return (
       <h1>val.username</h1>
     )
   })
    return (
      <div>
        {namesToRender}
      </div>
      )
     } 
}

All this is saying is "Go through that data and give me the name of each person and wrap it in some <h1> tags and spit that out".