I have a button set up to:
- make an API call to GET data and make a list out of the titles in the data;
- return those titles;
- update the "text" state of my component with those titles
- display those titles in a div
It appears that all of those things are happening; however perhaps not in order? I can tell that this.state.text updates with the titles as expected, but the DOM is not receiving the updated state. I have attached the code in a format that can be run in an 'index.js' file on a boilerplate React app.
I've tried messing with the order of operations, outputting the getAllPosts() function as an array, and a myriad of Array manipulations.
import React from 'react';
import ReactDOM from 'react-dom';
class AllPosts extends React.Component {
constructor(props) {
super(props);
this.state = {text: 'poop'};
}
getAllPosts(){
var request = new XMLHttpRequest();
var titles=[];
request.open('GET', 'http://jsonplaceholder.typicode.com/posts', true)
request.onload = function () {
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
data.forEach(post => {
titles.push(post.title);
})
} else {
console.log('error getting title list. Please try again.');
}
}
request.send();
console.log(titles);
return titles;
}
onClickButton = () => {
var allTitles = this.getAllPosts();
this.setState({text: allTitles});
console.log(this.state.text);
console.log(this.allTitles);
}
render() {
return (
<div>
<button
onClick={this.onClickButton}>
Get All Posts
</button>
<div>{this.state.text}</div>
</div>
);
}
}
function App() {
return (
<div className="App">
<header className="App-header">
<AllPosts />
</header>
</div>
);
}
export default App;
ReactDOM.render(<App />, document.getElementById('root'));
(have console open) Expected result is that the div text changes on click, from 'poop' to the list of titles. What's happening is that the data is 'undefined' and the text is blanked out. On clicking the button again, the list of titles will populate in console when I ask it to log this.state.text, so it's obviously getting to the state. But the state won't update on the page.