0

I have a button set up to:

  1. make an API call to GET data and make a list out of the titles in the data;
  2. return those titles;
  3. update the "text" state of my component with those titles
  4. 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.

3

3 Answers 3

1

You need to wrap your XMLHttpRequest in a promise:

getAllPosts = () => {
  new Promise((resolve, reject) => {
    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);
        })
        resolve(titles);
      } else {
        reject('error getting title list.  Please try again.');
      }
    }
    request.send()
  }).then(titles => {
    this.setState({ allTitles: titles })
  }).catch((error) => {
    console.log(error)
  })
}

Your onClickButton() should now just call getAllPosts() and nothing else.

onClickButton = () => {
  this.getAllPosts()
}
4
  • I tried your code example and the API call isn't happening now. The XHR request isn't being sent, it looks like? Aug 10, 2019 at 16:58
  • @n00bEternal Apologies, I forgot to add request.send(). I have updated my code to include it. Aug 10, 2019 at 17:03
  • 1
    No, I'm the one that should be apologizing. I compared your solution to my current product and should have seen that. I'm a n00b, but not that much of one :) Thank you! Aug 10, 2019 at 17:15
  • @n00bEternal Hey no worries! We're all noobs in some way or another :) Aug 10, 2019 at 21:27
0

Use Axios for API calls it will make your code much simpler and easier to work with, and much more visually appealing.

Comment if you have any questions about the code. Heres the documentation for Axios.

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';



class AllPosts extends React.Component {
    constructor(props) {
      super(props);
      this.state = {text: 'foo'};
    }

    async getAllPosts () {
      var titles = [];

      const response = await axios.get('http://jsonplaceholder.typicode.com/posts')
      const data = response.data;

      data.forEach((post) => {
          titles.push(post.title);
      })

      return titles;
    }  

    onClickButton = async () => {
      var allTitles = await this.getAllPosts();

      this.setState({ text: 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'));

0

You can wrap your request in Promise and return the promise from getAllPosts function.

getAllPosts = () => {
  return new Promise((resolve, reject) => {
    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);
        })
        resolve(titles);
      } else {
        console.log("fail")
        reject('error getting title list.  Please try again.');
      }
    }
    request.send();
  })
}

And your onClickButton function should be,

onClickButton = () => {
  let allTitles = this.getAllPosts();
  allTitles.then(titles => {
     console.log("success");
     this.setState({ text: titles })
  }).catch((error) => { 
     console.log(error)
  })
}

Another simple way is using fetch

getAllPosts = () => {
  fetch("http://jsonplaceholder.typicode.com/posts")
    .then(response => response.json())
    .then(titles => {
      console.log("success");
      let title = [];
      titles.forEach(post => {
          title.push(post.title);
      })
      this.setState({ text: title })
    }).catch((error) => {
        console.log(error)
    })
}

And your onClickButton function should be,

onClickButton = () => {
   this.getAllPosts();
}  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.