0

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))

1
  • React won't rerender a component if there is not a state or props change. I think you should have the logic of fetching the data elsewhere and pass them to the component via props. Commented Jan 19, 2019 at 8:05

1 Answer 1

2

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
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.