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'));
2
  • What about keeping the JSON file encoded and then decode it in render()? Otherwise take a look here: stackoverflow.com/questions/37997893/… Commented Feb 2, 2017 at 14:43
  • After reading your link,I figure out the problem!Thanks! Commented Feb 2, 2017 at 16:04

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

yeah thanks for the correct concept!I l figured what the problem was!Actually I just want to see the results on the <pre>,so then I use JSON.stringify to fix the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.