This is another one where I've had to kind of radically update my thinking, because, while I don't do a lot of AJAX-y data grabbing, I have had to do it in the past, and in the past, I've got some small muscle memory built up around using XMLHttpRequest
objects/methods. I mean, I couldn't actually do one from memory, anymore, but I do remember using them, and I do remember feeling like they were pretty gross.
But here in the modern age we have the Fetch API, which is dirt easy to use, once you know how to use it. And to be clear, I basically know how to use it, but I also don't understand every step in the history of JS that's gotten us from where we used to be (really wildly complex looking stuff) to where we are now (Promise
objects and async
functions—all of which I should go back through and actually explain better to myself, sometime!).
But I do kind of know basically where we're at now and that's that the fetch What's important to know here is that the fetch()
function is asynchronous—it returns a Promise
object which will "resolve" when the fetch action is done, so that things can be done with the results of the data—and so when we call fetch()
we need to await
it within an async
function.
Or, to put it another way, we need to stick some extra keywords in and around our functions, so that they behave the way we expect activities to behave.
So like in our sample code here our event listener function, which we attach to the button, is declared as an async function
, which lets us use the await
keyword inside it. From there, we can tell the browser to fetch
data from our (mock) api, but that we need to await
that data to be ready to be used—once it is, once our Promise
has become a Response
object, we can get a data object (in this case an array of objects) from the returned json by, well, calling the json()
method on the Response
object. Which then we can do whatever we want to with.