KAT
KAT

Reputation: 53

How to render data from API response in React?

how to initialize response from API to variable so I can use it in my render() function? Why component.setState is not working? Error:
Uncaught TypeError: Cannot read property 'username' of undefined(…)

class Main extends React.Component {
 constructor(props) {
     super(props);
    this.state = {
      data: 23
    };
 }

  componentDidMount() {
var component = this;


      fetch('https://fcctop100.herokuapp.com/api/fccusers/top/alltime')
          .then(function(response) {
              return response.json()
          }).then(function(json) {
              var data = json;
              console.log(data[0]);
              console.log(data[0].username);
              component.setState({
                  data: json
              })
          })

  }




  render() {
    return (
      <div>
        <h1>elo{this.state.data[0].username}</h1>


      </div>
    );
  }
}

const docs = document.getElementById('root');

ReactDOM.render( <Main/> , docs);

Upvotes: 2

Views: 8127

Answers (1)

Justin Herter
Justin Herter

Reputation: 590

The reason is that on first render this "this.state.data[0].username" is not set, until the response comes back from the API call.

Something like this in your render method should work:

render() {
    var someData = this.state.data[0].username || "";
    return (
      <div>
        <h1>elo{someData}</h1>


      </div>
    );
  }

Upvotes: 6

Related Questions