Michael Roberts Michael Roberts - 20 days ago 5
JSON Question

Accessing JSON data with react.js

This quesrtion relates to APIs, JSON formatted data and React.js.

I'm attempting to access data from an API for which the output is a JSON array, which is in the following format:

{
"success":true,
"timestamp":1479498608,
"source":"USD",
"quotes":{
"USDUSD":1,
"USDJPY":110.644997,
"USDCAD":1.351041,
"USDRUB":64.628403,
"USDCNY":6.879204,
"USDMXN":20.623699
}
}


Now the part that I am really interested in is the "quotes" values for various currency pairs.

So, using a
react.js
class:

var TickerTrader = React.createClass({
getInitialState: function() {
return{};
},
componentDidMount: function() {
var component = this;
$.get("http://apilayer.net/api/live?access_key=4a368d8077807c97b3aff9415a4d4995&currencies=USD,JPY,CAD,RUB,CNY,MXN&format=1", function(data) {
component.setState(data);
});
},
render: function() {
return (
<div>USD/JPY: {this.state.quotes.USDJPY}</div>
);
}
});


However, this does not seem to work. I was wondering, if I wanted to access the value corresponding to USDJPY, how would I go about doing this?

Answer

The issue isn't so much that the API call isn't updating state, it's that on your initial load quotes will be undefined, causing an error.

render: function() {
  // on initial load quotes will be undefined
  return (
    <div>USD/JPY: {this.state.quotes ? this.state.quotes.USDJPY : null}</div>
  );
}