Suomi Suomi - 3 months ago 75
React JSX Question

How to load and display data with React from an API running on localhost

I'm getting an error "app.js:16 Uncaught (in promise) TypeError: Cannot read property '0' of undefined" with my code below.

I'm trying to use React to display data from my Drupal API, that's running on my localhost.
In the React app, I'm using a simple HTTP server (python -m SimpleHTTPServer) to prevent XMLHttpRequest errors, and I have enabled CORS on my API. And instead of jQuery, I'm using Axios.

I can't get index.html to display anything else than the text "Event!", what am I doing wrong? Here is my app.js

class App extends React.Component {

constructor(props) {
super(props);
this.state = {
title: ''
}
}

componentDidMount() {
var th = this;
this.serverRequest =
axios.get(this.props.source)
.then(function(event) {
th.setState({
title: event.title[0].value
});
})
}

componentWillUnmount() {
this.serverRequest.abort();
}

render() {
return (
<div>
<h1>Event!</h1>
<h2>{this.state.title}</h2>
</div>
);
}
}

ReactDOM.render(
<App source="http://localhost:8888/drupal/api/events" />,
document.getElementById('container')
);


And here is my index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App</title>
</head>
<body>

<div id="container"></div>

<script src="https://npmcdn.com/react@15.3.1/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom@15.3.1/dist/react-dom.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://npmcdn.com/jquery@3.1.0/dist/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
<script type="text/babel" src="js/app.js"></script>

</body>
</html>


I can't get anything else than the text "Event!" to show up, what am I doing wrong?
Here is a screenshot of part of my API, that shows an example of the title I'm trying to display "EspooCine".

enter image description here

If I add console.log on ComponentDidMount(), e.g.:

componentDidMount() {
var th = this;
this.serverRequest = axios.get(this.props.source).then(function(result) {
console.log(result);
})
}


Then I get the following on the console:

enter image description here

Answer

Axios promises yield a response object on success that has a data property containing the body of the response; it appears that you are trying to access the [0] property of the response object, not of its data, which will be the Array you expect. Also, it looks like there are other mistakes made accessing the structure. Try this or something similar:

axios.get(this.props.source).then(event => {    
  th.setState({
    title: event.data[0].title[0].value
  });
});