Jason Chen Jason Chen - 4 months ago 9
Javascript Question

Using React to call Nested API?

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.

Answer

The problem is that you are using componentDidMount when you should use componentWillMount. Check out the documentation on these lifecycle methods.

This is what the documentation says about componentDidMount

Invoked once, only on the client (not on the server), immediately after the initial rendering occurs.

Which means when you first render your states are not declared unless you have used getInitialState before (another lifecycle method).

I simply did this:

componentWillMount: function () {
        this.setState({
            "farmer": [
                {
                "crops": "corn"
                }
            ],
            "activities":{
                "hobbies": "swimming"
            },
            "name": "Todd"
        });
    },

and I was able to use this.state.farmer[0].crops in my render method

EDIT:

To be clear. If you need to retrieve the data after you rendered the component then you need to specify default values for the states that you use in render. This can be achieved using getInitialState:

getInitialState: function () {
        return {
            "farmer": [
                {
                "crops": DEFAULT_VALUE
                }
            ],
            "activities":{
                "hobbies": DEFAULT_VALUE
            },
            "name": DEFAULT_VALUE
        });
    },
Comments