Emre Zinal
Emre Zinal

Reputation: 3

Cannot print string using ReactJS

I'm trying to get data from a web page and print the contents to screen. Here is the code for HTTP get request:

https.get('https://jsonplaceholder.typicode.com/users', (resp) => {
      let data = '';

      // A chunk of data has been received.
      resp.on('data', (chunk) => {
          data += chunk;
      });

      // The whole response has been received. Print out the result.
      resp.on('end', () => {
          for (let i = 0; i < JSON.parse(data).length; i++)
              cities += JSON.parse(data)[i].address.city + '\n';
          console.log(cities);
      });

At the code below i cannot print it to screen. I searched on Google but didn't come up with a solution.

let printing = "All users data:";
  return <div className="App">
      <header className="App-header">
          <p>
              {printing}
          </p>
          <p>
              {cities}
          </p>
      </header>
  </div>;

Here i can print the printing string but i can't print cities string.What is the reason for that? (Full code can be found at https://github.com/ezinal/reacttask/blob/master/src/App.js (39 lines))

Upvotes: 0

Views: 257

Answers (1)

Ntokozo Zwane
Ntokozo Zwane

Reputation: 1742

You are updating the state outside of the http request completion callback, so the state will be updated before the http request has completed i.e this.setState is called immediately after the http request is started, not after the request is completed. You need to move this.setState({cities : getCities}) into the resp.on('end', ...) callback, like this:

resp.on('end', () => {
    for (let i = 0; i < JSON.parse(data).length; i++)
        getCities += JSON.parse(data)[i].address.city + '\n';
    console.log(getCities);
    this.setState({cities : getCities}); // <-- update state here once http request has completed
});

Upvotes: 2

Related Questions