I have a function called request
that makes an AJAX call to an API, and returns some JSON data. RenderEntry creates an Entry component, which is basically just a div with an h3 element. The h3 element is supposed to come from the JSON data that is returned from request
.
In RenderEntry
, I am trying to call request
with the id
that is passed into it, assign it to the constant data
, and then pass data.name
into the Entry
as a prop. data
, however, is undefined.
In truth, this is my fist React app that I bootstrapped with create-react-app
. I know for a fact that request
works when you pass a literal id
into it, but I do not understand why it's not working in this function.
function Entry(props) {
return (
<div>
<h3>{props.name}</h3>
</div>
);
}
class App extends Component {
RenderEntry(id) {
const data = request(id);
console.log(request(id)); // undefined
console.log(data); // undefined
return <Entry name={data.name}/>
}
render() {
return (
this.RenderEntry(8000)
);
}
}
function request(id) {
const base = 'https://url.com/'
const request = new XMLHttpRequest();
request.open('GET', base + id, true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
const data = JSON.parse(this.response);
// console.log(data);
return data;
} else {
console.log('We reached our target server, but it returned an error!');
}
};
request.onerror = function() {
console.log('There was a connection error of some sort');
};
request.send();
}