Philipl
Philipl

Reputation: 415

Using query get JSON and use it in my React component

I am trying to access JSON data by Jquery $.getJSON function in my React component, but I keep getting this error:

Invariant Violation: Minified React error #31; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=31&args[]=object%20with%20keys%20%7Busername%2C%20img%2C%20alltime%2C%20recent%2C%20lastUpdate%7D&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

Objects are not valid as a React child (found: object with keys {username, img, alltime, recent, lastUpdate}).

This my code here.Don't quite know where the problem is.....

class Board extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      first: '',
      second: ''
    }
  }
  componentDidMount() {
    var self = this;
    $.getJSON("https://fcctop100.herokuapp.com/api/fccusers/top/recent",function(data){
      self.setState({first:data});
      console.log(this.state.first);
    });
  }
  render() {
    return (<div>
      <pre>{this.state.first}</pre>
      <pre>{this.state.second}</pre>
      </div>)
  }

}

ReactDOM.render(<Board />, document.getElementById('mine'));

Upvotes: 0

Views: 3767

Answers (1)

user1234511
user1234511

Reputation:

You cannot render an array of objects. React knows how to render components. A solution is to map over the array coming from the XHR response, and render each single object.

Your render function should look like:

class Board extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      first: [],
      second: []
    }
  }
  componentDidMount() {
    var self = this;
    $.getJSON("https://fcctop100.herokuapp.com/api/fccusers/top/recent",function(data){
      console.log(data)
      self.setState({first:data});
    });
  }
  render() {
    return (
      <div>
            {this.state.first.map((el, i) => <pre key={i}>{JSON.stringify(el, null, ' ')}</pre>)}
      </div>
    )
  }
}

ReactDOM.render(<Board />, document.getElementById('container'));

Also note I've changed the initial state to an empty array (in order to be able to map over it)

Upvotes: 1

Related Questions