What is Fetch?
fetch()method that provides an easy, logical way to fetch resources asynchronously across the network. -MDN web docs
To use the Fetch API, all we have to do is call fetch() and give it the URL as the first argument. Feel free to open up the developer tools and enter the following code into the console. It might take a second or two to log out the data, its hosted for free on heroku so it may need to fire up!
The example above is using a real URL that sends back JSON for us to use! Fetch returns a promise that contains the response. The response itself isn’t very useful at the moment but we can call .json() on the response to extract the json content. Calling .json() on our response also returns a promise with our JSON data passed to it. Now in our second .then() method we can use our data and update the DOM. Our json in this particular example is an array of objects.
Instead of console.log(ourData), let’s iterate over the array and create new html elements and attach them to the DOM.
Adding our JSON to the DOM!
In the above example, we are iterating over our array of objects and for each item the array, we are creating a new <p> html element, setting the innerText of that element to item.content (the post content in this example) and then attaching it to document.body.
We can also use Fetch to post data to the server!
We may want to save data to our database. We can use Fetch to also send data (again, usually in the form of JSON) to the server so we can persist the data.
This is just the beginning of the Fetch API. Once you wrap your head around using Fetch and manipulating the DOM based on the json data you should also start learning how to handle errors and using Fetch for other Restful actions.