Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed JavaScript Data Fetching!
You have completed JavaScript Data Fetching!
Preview
Discover how to use the Fetch API to make HTTP requests in a simpler, more readable way. Work with promises to fetch and use data from the Dog API.
Resources
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
In this video, we're gonna use
all the knowledge we've gained
0:00
to finally make real network requests
using the Fetch API.
0:03
Fetch is a modern built in browser
function that lets you make HTTP requests
0:07
just like we saw earlier with XHR,
except now in a much simpler, cleaner way.
0:12
And just in case you're wondering,
the reason it's called the fetch API
0:17
is because it's literally a tool
for fetching resources from a server.
0:21
While you've already learned
that APIs are ways to get or send data,
0:25
fetch emphasizes that this function is all
about requesting and retrieving data.
0:29
You give it a URL,
and it goes out to get the resource
0:34
for you,
returning a promise with a response.
0:36
It automates processes
for your JavaScript code handling the HTTP
0:40
request, response,
and asynchronous timing behind the scenes.
0:44
So let's take a look
at what we're gonna be doing here.
0:48
So since
0:52
it's called fetch,
I thought it'd be fun to use the dog API.
0:52
This is a free API and doesn't require
an API key to use, which is nice.
0:56
We've got a simple little web app that has
a select menu to choose a dog breed
1:02
and a random image of that type of breed
and a button to fetch another image.
1:06
But let's get right into this.
1:11
If you don't still have it
open, click the launch
1:12
workspace button below the video now.
1:14
So I've provided us with the HTML
and CSS already,
1:18
so we can jump straight
into the JavaScript.
1:21
In app dot js, I've also already declared
1:27
and defined variables grabbing the HTML
elements we'll be needing.
1:30
So let's start with the select menu
as everything else relies on that.
1:34
I'm gonna head to the
1:39
dog API's documentation
to get what we need.
1:39
I provided a link for you in the teacher's
notes below.
1:43
As you can see right here,
they're providing us an endpoint
1:46
which will return a list
of all the breeds they have.
1:48
This is almost perfect.
1:51
If you look at the structure
of what will be returned to us,
1:54
we see it's a JSON object named message,
and each of its keys are the breeds.
1:56
Each of those keys' values is an array
as some of them have sub breeds.
2:01
I don't wanna worry about sub breeds
for this little project,
2:06
so we could use this
and get each of the keys out of this
2:09
object and loop over those,
but I'm gonna be a little sneaky here.
2:12
For now, let's copy this endpoint
so we can use it in our code.
2:17
Okay.
2:22
Let's fetch these breeds.
2:22
I'm gonna go below
this fetch functions comment
2:24
and type the word fetch
and provide its parentheses.
2:27
Fetch requires at least one argument,
2:31
and that is the URL
you're wanting to fetch data from.
2:34
So I'll give it some quotes,
and within these, I'll paste our endpoint.
2:37
This will immediately return a promise
that represents your network request.
2:42
It will be in the promise's default
state of pending until our data arrives.
2:46
When the data arrives,
the promise is fulfilled.
2:51
If the request fails,
the promise is rejected.
2:54
Now here's where I'm gonna be
a little sneaky.
2:57
To save us a few extra steps
working with an object and its keys,
2:59
I'm actually going to delete the slash
all from the end of this URL.
3:03
They don't mention this
in their documentation anymore,
3:07
and I only know about this
because I used it years ago.
3:10
But this will actually just return
an array of the master breeds,
3:13
no sub breeds,
which is exactly what we want.
3:16
So just like we saw with promises,
we can chain
3:20
then and catch methods
right onto this fetch method.
3:22
And as we saw in the documentation,
we're getting a JSON object back.
3:25
So the first order of business is parsing
this JSON
3:30
to a JavaScript object that we can use.
3:33
So I'll chain the
then method and provide it
3:36
an arrow function just like before.
3:38
We're taking the response here,
3:41
so I'll name it that, and I'm just going
to console log this response.
3:42
Let's open our preview.
3:50
Let's open the dev tools
3:53
and the console tab.
3:55
And here we see our response.
3:59
You can see the status
and other information,
4:02
but what we're interested in lives
inside this body property.
4:04
Currently, we can't do anything with it,
so let's go fix that.
4:09
Let's remove this console log
and use the JSON method on our response.
4:13
This is going to find
and read the body of the request
4:18
and parse this to a JavaScript object
that we can actually use in our code.
4:21
Awesome.
4:26
Let's chain another then method.
4:27
Take the data,
which is now a JavaScript object.
4:32
I usually name these response and data,
but they're just parameter names.
4:35
You can name them whatever you'd like.
4:39
And I'll console log that.
4:41
Let's check it now.
4:45
Let's refresh the preview,
and there we go.
4:46
So we have an object with a key
named message and another named status.
4:50
Our message key's value is the array
we want to use.
4:55
Awesome.
4:58
Oh, and if you're seeing it
as two separate arrays here, don't worry.
4:59
This is just done
by the dev tools in the browser.
5:03
Our message value in our code
will be just one array.
5:06
Here, I'll show you real quick.
5:09
Let's change this console log
to specifically
5:10
grab the message property
with dot notation.
5:13
Let's inspect this again.
5:16
Perfect.
5:19
See, it's really just one array
with, well, at least
5:19
at the time of filming this, a 108 items.
5:22
But the DevTools breaks it up
for visibility in the browser.
5:25
Nice job. You're fetching data.
5:29
So this gives us a nice predictable chain.
5:32
Request, response, parsed data.
5:35
See how much easier
this is compared to that XHR we looked at?
5:38
So now what do we want to do?
5:42
We want to loop over each item
in this array
5:44
and create an option for our select menu,
then append it to the select menu.
5:47
Let's do it.
5:51
Now we could do all of this
right here in the then method,
5:53
but this is a perfect opportunity
to create a separate function
5:56
to keep our code
readable and maintainable.
5:59
So let's go down below this
6:03
UI helper functions
comment and create one.
6:05
I'll name it populate breed options.
6:08
And this will take in our array of breeds,
6:15
so I'll name the parameter breeds.
6:17
And before I forget, I'll go back up here
6:20
and call this method
passing in our data dot message.
6:23
Great.
6:32
Okay.
6:33
Now I'm gonna kick off a for each loop
because we want to iterate
6:34
over every single item
in this breeds array.
6:37
So breeds dot for each.
6:41
We'll just name each item breed
6:46
and open up our arrow function.
6:48
Okay.
6:53
We want to create a new element,
6:53
and we'll need to
6:55
do a few things to it after,
so let's store it in a local variable.
6:56
Const.
7:00
I'll name it option
and set this equal to document
7:01
dot createElement
7:06
and pass in the string option.
7:11
Options have both a value attribute
7:16
and the text the user sees in the menu,
so let's set those.
7:18
Option dot value equals breed
7:21
and option dot text content equals breed.
7:26
Nice.
7:33
Now we need to append this
to our select menu.
7:34
As you can see up top here,
I already have that element selected,
7:37
so I'm gonna copy that.
7:41
So let's say
7:47
select menu dot append child and pass
7:48
in our new option.
7:50
Let's save and refresh
7:55
our preview to check it's all working.
7:57
Nice.
8:00
We can see it has the first value selected
by default, which is Affenpinscher.
8:01
And when we open it,
we have this huge list of breeds.
8:04
This is fantastic.
8:08
One last thing we should do for
our safekeeping is tack on a catch
8:10
method just in case
we encounter a rejected promise.
8:13
Let's do that.
8:16
So at the bottom here, we'll add a catch.
8:18
We'll name the parameter error,
8:23
and we'll just console dot error,
a template
8:26
literal.
8:28
Error fetching data,
8:32
and let's plug in our error there.
8:36
So let's trigger this to see it in action.
8:41
I'll just add some letters
to ruin our endpoint here.
8:43
Save and refresh the preview.
8:46
There we can see we got a four zero four
not found error and our catch error there.
8:49
Now this error isn't exactly ideal,
and we'll get to that shortly.
8:54
Don't worry.
8:58
Let's go back and fix this URL
before we forget.
8:59
There we go.
9:05
Nice work here.
9:07
We're not only fetching data
in a modern and streamlined
9:08
fashion,
we're already displaying it in our app.
9:11
Our key takeaways
are that fetch returns a promise.
9:14
If it's resolved, we,
9:17
at least most of the time,
are getting JSON back in our response,
9:19
so we need to parse that response's body
to a JavaScript object.
9:22
Lastly, we use catch to catch any rejected
requests.
9:27
We've still got some fun work to do here,
so we'll get right to it after this quiz.
9:31
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up