So I am trying to have a text element that displays a certain child from JSON (gotten using fetch). I have trying setting the response from fetch equal to this.state.json (declared in the constructor). Then I use a Text element with this.state.json.current.name (which is a valid child in the Airtime API), but I get an error saying undefined is not an object while evaluating this.state.json.current.name. I have tried making the function synchronous and asynchronous (I thought maybe the JSON wasn't loaded while text tried to be displayed), but nothing worked.
fetchJSON = async () => {
fetch('http://IPADDRESS/api/live-info', {
method: 'get',
dataType: 'jsonp',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then((response) => {
return response.json()
}).then((responseData) => {
this.setState({json: responseData})
this.setState({isLoadedJSON: true})
return responseData;
})
.catch(function(err) {
console.log(err);
})
}
then I just call await this.fetchJSON() in componentWillMount().
For displaying text I just have <Text>{this.state.json.current.name}</Text>, but this doesn't work and I'm not sure if its a React issue or my issue. this.state.json.env works fine, but any further nested items, such as this.state.json.current.name, It displays undefined is not an object. I have also tried having an isLoadedJSON state and either an if or while before rendering, so it render a blank View while JSON is loading, but that then displays a blank View for ever.
Any thanks would be very highly appreciated.
{
"env": "production",
"schedulerTime": "2018-02-15 13:37:50",
"previous": {
"name": "REDACTED",
"starts": "2018-02-15 08:15:00",
"ends": "2018-02-15 08:29:51.611",
"type": "track"
},
"current": {
"name": " - TVP",
"starts": "2018-02-15 09:20:00",
"ends": "2018-02-15 10:00:00",
"media_item_played": true,
"record": 0,
"type": "track"
},
"next": {
"name": "REDACTED",
"starts": "2018-02-15 11:10:00",
"ends": "2018-02-15 11:15:06.077",
"type": "track"
},
"currentShow": [
{
"0": "2018-02-15 09:20:00",
"1": "2018-02-15 10:00:00",
"2": "REDACTED",
"3": 33,
"4": 273,
"5": 0,
"6": "",
"7": "2018-02-15 09:20:00",
"8": "2018-02-15 10:00:00",
"start_timestamp": "2018-02-15 13:20:00",
"end_timestamp": "2018-02-15 14:00:00",
"name": "REDACTED",
"id": 33,
"instance_id": 273,
"record": 0,
"url": "",
"starts": "2018-02-15 13:20:00",
"ends": "2018-02-15 14:00:00"
}
],
"nextShow": [
{
"id": 23,
"instance_id": 138,
"name": "REDACTED",
"url": "",
"start_timestamp": "2018-02-15 15:10:00",
"end_timestamp": "2018-02-15 15:20:00",
"starts": "2018-02-15 15:10:00",
"ends": "2018-02-15 15:20:00",
"record": 0,
"type": "show"
}
],
"timezone": "GST",
"timezoneOffset": "14400",
"AIRTIME_API_VERSION": "1.1"
}
responseData? And I would recommend you to callfetchJSONinsidecomponentDidMountinstead ofcomponentWillMount. More about that you can read on this nice article daveceddia.com/…