0

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'));
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Philipl
  • 395
  • 4
  • 21
  • What about keeping the JSON file encoded and then decode it in render()? Otherwise take a look here: http://stackoverflow.com/questions/37997893/promise-error-objects-are-not-valid-as-a-react-child – Theraloss Feb 02 '17 at 14:43
  • After reading your link,I figure out the problem!Thanks! – Philipl Feb 02 '17 at 16:04

1 Answers1

1

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)

  • yeah thanks for the correct concept!I l figured what the problem was!Actually I just want to see the results on the
    ,so then I use JSON.stringify to fix the problem.
    – Philipl Feb 02 '17 at 16:04