2

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);
2
  • You should have a guard statement / ternary operator in your render method if you plan on using some data that will arrive at a later time. Something like this: var someData = this.state.data[0].username || ""; Commented Nov 14, 2016 at 17:07
  • @JustinHerter console.logs in fetch logs proper data Commented Nov 14, 2016 at 17:13

1 Answer 1

6

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

2 Comments

I'm getting parsing error when i put variable in return statement. SyntaxError: Unexpected token (39:6) while parsing file I'm using browserify + babelify in my gulpfile
@KAT sorry my mistake, I moved the declaration outside the return function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.