Making AJAX Requests in React With XHR
Today, I got the kick in the pants I needed to finally write about one of my latest React projects: Number Marriage Equality. The inception for this project occurred a few years ago, when I wrote a messy Python script called Number Marriage. This is the “front-end”:

Later, when I joined the Flatiron School, I realized I could re-write this app in React so that people could actually enjoy it without having to deal with the code — and actually use OOP concepts this time around. It was a lot of fun! I did meet one person who wasn’t impressed, though.
A Brief Detour…
Ladies, have you ever told someone that you code, get a bunch of patronizing comments, but then start to realize that the person patronizing you knows less than you do?
Today, I was working in a cafe when a young man next to me commented on my open terminal emulator. He said “You code? I code!” Then he went on and on about it, not really caring what I said. I was thinking about just leaving the cafe, but then he sent me a bunch of his poetry. “Art exchanging can be fun,” I thought, so I shared Number Marriage Equality in response.
He was not a fan. (I know, what could be more boring than letting ASCII characters get married?) But he immediately started looking for the code anyway. So I just showed him how to find it with Chrome Developer Tools, and this is roughly what he saw first:
[...]class App extends Component {
constructor(){
super()
this.state = {
story: {},
storyLength: 0,
step: 0,
currentChapter: {chapter: '', placeholder: '', newVariable: ''},
bride: null,
groom: null,
married: false,
consumation: null,
objection: false,
endReached: false
}
this.advanceStory = this.advanceStory.bind(this)
this.restartApp = this.restartApp.bind(this)
this.handleBrideAndGroom = this.handleBrideAndGroom.bind(this)
}componentDidMount(){
var xhr = new XMLHttpRequest()
xhr.open("GET", './story.json', true)
xhr.onload = function(e){
if (xhr.readyState === 4){
if (xhr.status === 200){
var story = JSON.parse(xhr.response).story
this.setState({
story: story,
storyLength: story.length,
currentChapter: story[0]
})
} else {
console.error(xhr.statusText)
}
}
}.bind(this)xhr.onerror = function(e){
console.error(xhr.statusText)
}
xhr.send(null)
}[...]
For those of you unfamiliar with React, this is the main App component, its constructor, and a life-cycle function called componentDidMount, which, as you may have guessed, runs after a React component mounts. The maintainers of the React library recommend doing external requests here, stating that “Setting state in this method will trigger a re-rendering.”
That guy took a cursory look at the code and immediately said “If you’re going to share your code with other people, you can’t use names like ‘XHR’ because they don’t know what you’re talking about.”
Not completely paying attention, I said “It’s great if you prefer Fetch or something else, but for this project I used XHR. Both APIs work.” Then I left because I wasn’t getting enough work done at this place. When I got home, though, it dawned on me that he wasn’t dissing XHR: He simply didn’t know what XHR was and thought he was giving advice about semantic code.
Generally, when you don’t know what something is, it’s good to find out what it is before you give advice about it.
And that’s exactly what I’d like to talk about in today’s post.
What Is XHR?
An XHR object is a shorter way of referring to an XMLHttpRequest object. It is made available by the XMLHttpRequest API, which allows you to make asynchronous HTTP requests, also known as AJAX requests.
When you use XHR, first you create a new request object: var xhr = new XMLHttpRequest();
Then, you call various functions on that object to make your request:
xhr.open("GET", './story.json', true)
xhr.onload = function(e){
if (xhr.readyState === 4){
if (xhr.status === 200){
var story = JSON.parse(xhr.response).story
this.setState({
story: story,
storyLength: story.length,
currentChapter: story[0]
})
} else {
console.error(xhr.statusText)
}
}
}Finally, to actually send the request, run xhr.send();
A request object itself does not return the data you are requesting — because it’s not a function. Rather, an XHR object is just that: a Javascript object, which contains functions that allow you to make a request and access information from that request. I think of an XHR object like a set of tools. This makes “xhr” quite semantic for my purposes.
What’s in a Name?
How would YOU name your XHR object? Should you call it xhr, xhttp, xHttpReq, xhRequestObject, xmlHttpRequest? I’ve seen all of those, and they are all descriptive.
That guy didn’t think “XHR” was semantic, but I would encourage him to simply Google “XHR” or look on Wikipedia to see just how many other people recognize the abbreviation. But also, how would you feel if you went by T.J. your whole life and someone’s just like “No! That’s not your name! No abbreviations!”
With that, I encourage you to take a look at XHR for yourself. Or Fetch. Or jQuery. Or another library that takes requests.
