To use Fetch, you also need to be able to do two things:
- Send a request with XHR
- Receive a response with XHR
This process is a lot faster and easier compared to XHR.
Sending a request
To send a request, you just need to pass in a url (the endpoint) into fetch.
You can then pass in any options into fetch as a second variable. These options are, well, optional.
fetch('http://link-to-resource', options)We’ll talk about what these options are later. For now, just follow along to get a rough understanding of the process.
If you want to get a list of my repositories from GitHub, you can use the following endpoint.
fetch('https://api.github.com/users/zellwk/repos')Receiving a response
To receive a response, you add a then method after fetch.
This then method receives the response from the API server.
fetch('https://api.github.com/users/zellwk/repos') .then(response => { console.log(response) })
The body property contains the data we want.
In this case, the body is a ReadableStream. (Click on the three dots and they’ll be replaced with ReadableStream).
Now, you don’t have to understand what a ReadableStream is to be able to use the response from the Fetch API.
You just need to know two things:
- What is the type of data being sent back
- How to convert that data back into JavaScript
In this case, GitHub sends JSON data back to us.
To convert JSON data into a JavaScript object in the Fetch API, we need to use the response.json method.
fetch('https://api.github.com/users/zellwk/repos').then(response => response.json(),)Once you do this, you can get the data in the next then method.
fetch('https://api.github.com/users/zellwk/repos') .then(response => response.json()) .then(data => { console.log(data) // Do something with the data })
Wrapping Up
Here’s the full code you need to fetch a resource with the Fetch API.
fetch('https://api.github.com/users/zellwk/repos') .then(response => response.json()) .then(data => { console.log(data) // Do something with the data })As you can see, it’s much simpler compared to the XHR variant. This is why people prefer raw Fetch over raw XHR.
That said, we can make things even easier with libraries.
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