The Fetch API (Fetch from now on) is a newer method that lets you perform Ajax. It is a better alternative compared to XHR. It can be used in newer technologies, like Service Workers, where XHR is discouraged.
(We wonβt be covering Service Workers in this course).
Fetching with Fetch
To send a request with Fetch, you use the fetch method.
fetch(url, options)url is the address you want to request information from.
options is a JavaScript object that lets you provide extra options. Weβll examine the options in a later lesson.
Hereβs the fetch request to get a list of my Github repositories.
fetch('https://api.github.com/users/zellwk/repos')Note: Fetch sends out your request immediately when you write fetch. This is unlike XHR, where you send the request with send method.
The response from Fetch
To see the response from Fetch, you need to write a then statement.
fetch('https://api.github.com/users/zellwk/repos').then(response => console.log(response),)
The response looks different from an XHRβs response. The data we want is hidden in the body property as a readable stream.
We need to convert this readable stream into JavaScript before we can use it. To do so, we use the json method that comes with a Fetch response.
You will be able to see the data you requested with a second then call.
fetch('https://api.github.com/users/zellwk/repos') .then(response => response.json()) .then(data => console.log(data))
Handling the data
The rest is similarβyou need to massage the data before you can use it.
fetch('https://api.github.com/users/zellwk/repos') .then(response => response.json()) .then(data => { // Massage data and output to DOM here })Wrapping up
Fetch is based on promises. If we want to understand fetch and the whole then thing, we need to know what promises are and how they work.
Exercise
Do this:
- Send a request to Github with Fetch. Ask for a list of your repositories.
- Display a list of repositories that have more than 50 stars.
Welcome! Unfortunately, you donβt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson