Say I had the following JSON file:
{
"farmer": [
{
"crops": "corn"
}
],
"activities":{
"hobbies": "swimming"
},
"name: Todd"
}
I would like to know how to make calls to them using React. My best attempt is as shown below.
componentDidMount: function(){
var selfish = this;
$.get('~~someurl~~', function(data){
selfish.setState(data);
});
},
render: function(){
return (<div>
<p>{this.state.name}</p>
<p>{this.state.activities.hobbies}</p>
<p>{this.state.farmer[0].crops}</p>
</div>)
}
I get that the first one {this.state.name} will run as it has been written. However, I am uncertain as to how to express the final two {this.state.activities.hobbies} and {this.state.farmer[0].crops} using the React syntax.
I have written them out in hopefully a way that expresses what I am trying to achieve with each call.
EDIT: The specific error that results from the latter two state that they are undefined.
EDIT: So I got the second one working by adding an empty initial state.
getInitialState: function(){
return {activities: '', farmer: ''}
}
However, this leaves the last one, which still returns an error.
{...}is just normal JavaScript (there is no specific "React syntax").this.state.activities.hobbiesetc will work as long as the data exists. I assume that on the initial render the data doesn't exist. In that case you first have to think about how the UI should look like if the data is not present. Testing for the existence of the data / property works as usual, e.g.this.state.activities && this.state.activities.hobbies. There is nothing React specific about it.{this.state.name}. Because{this.state.name}loads just as soon as I render.this.state.activitiesdoesn't exist the first time, you will get an error. So you either have to check beforehand whether the value exist (and render something depending on that check) or you have to provide a default state to the component, e.g. with an emptythis.state.activitiesobject. Here is a simplified example of the issue you are experiencing:var state = {}; console.log(state.activities.hobbies);This will throw an error becausestatedoesn't have any properties. Now, I can either add an initial value or test before logging.activitieson initial load. Now, I'm still unsure of the last part{this.state.farmer[0].crops}. Having an emptyfarmer: ''on initial state does not solve this.this.state.farmer[0].cropsexpectsfarmerto be an an array containing an object.farmer: ''setsfarmerto an empty string instead. Typevar farmer = ''; console.log(farmer[0])in your browser's console and see what the result is. If you go with the default state, then you need to initialize the state with values similar to the ones you expect.