Michael Roberts Michael Roberts - 1 year ago 63
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:


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

So, using a

var TickerTrader = React.createClass({
getInitialState: function() {
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) {
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 Source

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 = {}
// undefined
// Uncaugt TypeError: Cannot read property 'fail' of undefined
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download