Playing Fetch, But Not With An Animal
Fetch requests, as Flatiron explained to us, is a way to execute a technique known as AJAX. AJAX is used to present a page quickly to a user (QUICKLY being extremely important, as we know the average user doesn’t have the patience to wait through a long page load) and then add more information to the DOM after the page loads. Fetch allows us an easy entrance to employing AJAX for our applications.
Let’s check out a basic “GET” fetch request
The fetch request initially takes in a baseUrl (in this case it’s out of frame, but it’s http://localhost:3000). If we go into our console and add a breakpoint in the function on line 9 we see that resp is somewhat hard to understand:
Not the best! in that same line, we convert the response to json on line 11, which ends up looking significantly more readable:
That’s much better! At this point, we iterate over that array of data (which looks strikingly similar to our API, I might add) and get each individual element of that array to add to our DOM to appear on our webpage:
After each element is isolated, it’s passed into a new function elsewhere in our code to attach to the DOM and allow our users to begin to manipulate it.