API data isn't being assigned to a global variable property

I’m trying to assign the data to globals.content but it’s throwing a type error. Anyone see the issue?

EDIT: Looks like the console.log executes too fast due to the request being async. Answer is to run a conditional (if statement) to check for status code 200 and readystate 3 (meaning the request is done)

var xhr = new XMLHttpRequest() // Access inbuilt props and methods on this object
xhr.open('GET', 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1', true) //last value says "run this request async"
xhr.send()

xhr.addEventListener("readystatechange", processRequest, false) //listening for the readystatechange property to be changed

xhr.onreadystatechange = processRequest

var globals = {
  response: {}
}

function processRequest(responseEvent) {
  if (xhr.readyState === 4 && xhr.status === 200) {
    globals.response = JSON.parse(xhr.responseText) //parsing turns a long string into an object

    // var response = JSON.parse(xhr.responseText) //parsing turns a long string into an object
    // console.log(response[0].content + " response[0].content local scoped")
  }
}

console.log(globals.response[0].content)

my recommendation would be to take advantage of the fact that async calls return a Promise and thus are thenable (i.e., you can structure code to run only after the async call is returned).

A couple useful links:

https://www.promisejs.org/

http://www.mattgreer.org/articles/promises-in-wicked-detail/

1 Like