0

I want to fetch some values from a json file and render them in multiple components. This code doesn't seem to work. Please suggest any changes. probably there are some issues with scope.

var App = React.createClass({

    getInitialState: function(){
      return { myData: [] }

    },
    showResults: function(response){
        this.setState(
          {myData: response}
          )
    },

    loadData: function(URL) {
      $.ajax({
        type: 'GET',
        dataType: 'jsonp',
        url: URL,
        success: function(response){
          this.showResults(response)
        }.bind(this)
      })
    },

    render: function(){
      this.loadData("fileLocation/sample.json");
      return(
        <div>
        {myData.key1}
        <Component1 value={myData.key2} />
        <Component2 value={myData.array[0].key3}/>
        </div>
      )
    }
  });

  var Component1 = React.createClass({
    render: function () {
      return(
        <div>{this.props.value}</div>
      )
    }
  });

  var Component2 = React.createClass({
    render: function () {
      return(
        <div>{this.props.value}</div>
      )
    }
  });
  ReactDOM.render(<App/>, document.getElementById('content'));

This is sample.json file I'm trying to fetch from. Even this shows a syntax error

{
  key1:"value1",
  key2:"value2",
  array: [
    {key3:"value3"},
    {key4:"value4"}
  ]
}
4
  • 2
    Shouldn't myData. be this.state.myData.? Commented May 2, 2016 at 13:14
  • 2
    Also, call this.loadData() in the componentDidMount or componentWillMount. Else, it'll infinitely call due to state change. Commented May 2, 2016 at 13:17
  • In addition to @Kujira tips, the .bind(this) is referring to the xhr object. Assign an alias to this outside the $.ajax at the beginning of loadData function, and then utilize the alias at the success callback to refer to the actual this that you want. Commented May 2, 2016 at 15:18
  • @falsarella can you please write the modified code. I am new to programming Commented May 3, 2016 at 6:12

1 Answer 1

1

Properly call showResults at loadData [1]:

var App = React.createClass({

    getInitialState: function(){
      return { myData: [] };
    },

    showResults: function(response){
        this.setState({
            myData: response
        });
    },

    loadData: function(URL) {
      var that = this;
      $.ajax({
        type: 'GET',
        dataType: 'json',
        url: URL,
        success: function(response){
          that.showResults(response);
        }
      })
    },

Move loadData from render to componentDidMount [2], and properly access myData [3]:

    componentDidMount: function() {
      this.loadData("fileLocation/sample.json");
    },

    render: function(){
      return(
        <div>
        {this.state.myData.key1}
        <Component1 value={this.state.myData.key2} />
        <Component2 value={this.state.myData.array[0].key3}/>
        </div>
      )
    }
});

Keep Component1 and Component2 as they already are:

var Component1 = React.createClass({
    render: function () {
      return(
        <div>{this.props.value}</div>
      )
    }
});

var Component2 = React.createClass({
    render: function () {
      return(
        <div>{this.props.value}</div>
      )
    }
});
ReactDOM.render(<App/>, document.getElementById('content'));
Sign up to request clarification or add additional context in comments.

6 Comments

@VishnuPaspunoor Don't just copy-paste: try to understand the reasoning behind each change! :)
Thank you for this. I'll surely understand
how to do this without using jquery? Can we do this using jsx?
I am getting this error: jquery.min.js:4 GET localhost/React/projects/… 404 (Not Found)
@VishnuPaspunoor You can do the ajax with any library you want, I'd recommend Zepto or Axios. Try to debug or log things to troubleshoot the error you're getting. Basically, you're trying to fetch a file or an endpoint that doesn't exist (404 Not Found). A great start point is the ajax URL - review if it's correct.
|

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.