Michael Roberts Michael Roberts - 16 days ago 6
React JSX Question

Uncaugt TypeError 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. This is actually Javascript related, not React.

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

Conversely, you could load the initial schema in the state.

getInitialState: function() {
  return {
    quotes: {}
  };
},

Javascript seems to be ok with returning an undefined when the property doesn't exist, but it will raise an exception when the object you're accessing the property from is undefined.

let foo = {}
foo.test
// undefined
foo.test.fail
// Uncaugt TypeError: Cannot read property 'fail' of undefined
Comments