First I’ll go over the most basic example of using fetch, then I will also go over using it with the new async/await way of handling requests.
The most basic way of handling a fetch request is you start of with the fetch() method and pass a URL for the resource in as a option like so:
The next part is the .then method that returns a promise result which is set up the following way:
A shortcut method for retuning JSON from the response would be to add another .then method doing the following:
You can also use fetch to post data. You would do that by adding a configuration object after the URL that includes a method parameter, header parameter, and a body parameter that represents the data being posted. This can be done by the following way:
In this example I’m posting a JSON object that contains the username value to an end point.
Another way of using fetch to get data is with async functions with the await keyword. Most modern browsers support this but like I said before you’re better off using Babel with your project if you’re going to use this.
For this there are 2 main parts. The first part is the async keyword which you place before the function you want to use it in. The second part is using the await keyword which is used within the async function. The await keyword can be used when calling a function that returns a promise such as fetch. You can use it the following way:
If you want to handle errors you can also use the tray catch structure. This would show any errors you get when attempting to fetch your resource. This structure would look like the following: