Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous xmlhttp request in react

I am trying to implement asynchronous XMLHttpRequest in react. Here is my attempt:

var xhr = new XMLHttpRequest();
var json_obj, status = false;
xhr.open("GET", "https://jsonplaceholder.typicode.com/photos/", true);
xhr.onload = function (e) {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      json_obj = xhr.responseText;
      status = true;
    } else {
      console.error(xhr.statusText);
    }
  }
};
xhr.onerror = function (e) {
  console.error(xhr.statusText);
};
xhr.send(null);

class Welcome extends React.Component {
  render() {
    return (
      <div>
          <img src= {status ?  json_obj[0].url : 'loading...'}></img>
      </div>
    );
  }
}
ReactDOM.render(
   <Welcome/>,
   document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

I have been thinking about adding listener to it but i don't know how to do it.

Overall i am having problem with an update after async XMLHttpRequest loads and returns value.

like image 203
Mac Avatar asked Aug 15 '17 21:08

Mac


People also ask

Does React use XMLHttpRequest?

Making HTTP requests using XMLHttp​Request Sending HTTP request from your react app is quite simple. In fact, you don't even need to use a library to do this. All we need to do to send a simple GET request is to create a new XMLHttpRequest, add an event listener to it, open the URL and send the request.

What is the purpose of XMLHttpRequest?

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.

Should I use fetch or XMLHttpRequest?

Fetch is a new native JavaScript API, supported by most browsers today. Fetch allows you to make network requests similar to XMLHttpRequest . According to Google Developers Documentation Fetch makes it easier to make asynchronous requests and handle responses better than with the older XMLHttpRequest .

Is XHR deprecated?

Synchronous XHR is now deprecated and should be avoided in favor of asynchronous requests.


1 Answers

It is recommended to make AJAX calls in the componentDidMount lifecycle method.

componentDidMount is for side effects. Adding event listeners, AJAX, mutating the DOM, etc.

Also, you should consider using the new fetch API.

class Welcome extends React.Component {
  constructor() {
    this.state = {
      data: null,
    };
  }

  componentDidMount() {
    fetch('https://jsonplaceholder.typicode.com/photos/').then(response => {
      return response.json();
    }).then(json => {
        this.setState({ data: json});
    }).catch(error);
  }

  render() {
    if (this.state.data) {
      return <img src={this.state.data[0].url} />
    }
    else {
      return <div>Loading...</div>
    }
  }
}
like image 113
Paul Fitzgerald Avatar answered Oct 05 '22 11:10

Paul Fitzgerald