Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Learn to use the Fetch API, a data-fetching interface native to the browser, to load external data and update state in React.
Trending GIFs Endpoint
https://api.giphy.com/v1/gifs/trending?api_key=<ENTER YOUR API KEY HERE>&limit=24&rating=g
Resources
React DevTools
Treehouse Courses and Workshops
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
[MUSIC]
0:00
Hey everyone.
0:09
I'm Laura,
a JavaScript instructor here at Treehouse.
0:10
In this workshop, I'll teach you
a couple of different ways to fetch
0:14
external data with React, and
how to display the data in your app.
0:19
We're going to create this fun GIF
searching app using the GIPHY API
0:25
from giphy.com, a GIF search engine where
users can search for reaction GIFs.
0:31
So, I'm going to assume that
you know the basics of React.
0:37
Like creating and rendering components,
0:41
passing props to components,
and managing state.
0:45
If you're not sure what this means,
be sure to check the teacher's notes for
0:49
links to Treehouse courses and workshops
that'll get you up to speed with React.
0:54
To code along with me, download
the project files for this workshop.
0:59
Navigate to the START-HERE folder and
1:03
open up the project files in
your favorite text editor.
1:06
I'll be using Visual Studio Code.
1:10
Open up the terminal by pressing
Command J, or this button right here.
1:12
Make sure you're in
the gif-search directory, and
1:18
run npm i to install
the project dependencies
1:23
Then npm start to run
the app in the browser.
1:28
By now you know that React
is just a view library,
1:34
that simply renders components using
the state and properties passed to them.
1:37
React itself doesn't have a built
in way to fetch data from a server,
1:43
in fact, since Reacts' only
concern is rendering views,
1:48
it doesn't even know
that there is a server.
1:53
So, there are several
JavaScript methods and
1:57
tools you can use to fetch
data in a React app.
2:00
The two methods I'll cover in
this workshop are the Fetch API,
2:04
a data fetching interface
that's native to the browser,
2:09
and Axios, a popular tool that's similar
to Fetch with a few key differences and
2:13
advantages.
2:19
Both of these are promise-based
approaches, meaning that they use
2:20
JavaScript promises to handle
the results we get back from the server.
2:25
You can learn a whole lot more about
JavaScript promises by watching
2:30
the Treehouse workshop I
posted in the teacher's notes.
2:34
In the app, we'll write all our
data fetching code here in App.js.
2:39
This app component is the main
container of the app.
2:46
It's responsible for rendering
the child components of the app, like
2:50
a list of GIFs, and it's going to pass
them the external data as state via props.
2:55
So, the first thing we'll do is define
an initial state inside the App function.
3:01
We'll start off by importing
the useState hook,
3:08
we'll add a comma,
curly braces, and useState.
3:13
At the top of the app function,
let's type const [] = useState().
3:19
Now the state in our app is going to
be the GIF data we want to display.
3:29
So let's call this state gifs, and
the function to update it to setGifs.
3:36
And we'll set the initial
value to an empty array.
3:42
The gifs state now represents a collection
of objects that will change and
3:47
be updated by components.
3:53
Next, right below the state declaration,
3:55
we're going to set up all our data
fetching inside Reacts' useEffect hook.
3:58
If you need to load external data right
when a component gets mounted to the DOM,
4:06
or if your request is dependent on
another variable like a search term,
4:12
this is a good place to create
the request because useEffect allows us
4:17
to control when the data is fetched.
4:22
If you're using Visual Studio Code,
you may have noticed the useEffect hook
4:26
was automatically added to the import
statement at the top of the file.
4:31
If that's not the case, be sure to
import the useEffect hook, like so.
4:36
As you may remember, the useEffect
hook takes in two parameters,
4:43
the setup function and
an optional dependency array.
4:49
Right now for
4:53
our app I want the data to be fetched
immediately after the component mounts.
4:54
So for the second parameter,
I'll pass an empty array.
5:00
Inside useEffect's setup function,
5:05
we'll add the fetch method to start
the process of fetching our data.
5:08
Fetch provides a simple way to make
web requests in the browser and
5:14
handle responses.
5:19
In the fetch method, we define the path or
5:20
URL to the resource we want to fetch,
so in our case the GIPHY API.
5:24
So the GIPHY API is open to the public,
5:30
you can check out all the different
endpoints here in the GIPHY API docs.
5:33
For this example, I'm going to return
the data from the trending GIFs endpoint.
5:40
I'll copy over the GIF URL and
pass it to the fetch method as a string.
5:46
Our URL isn't quite ready,
one thing we're missing
5:53
is the HTTPS in front of the GIF URL,
so lets include that.
5:58
We'll type https://.
6:04
Also, if you take a look back
at the API docs, you'll notice
6:09
that the API key is the only
request parameter that is required.
6:14
I'll copy the request parameter and
navigate over to App.js.
6:20
To add parameters to our URL,
6:26
add a question mark to the end of the
GIF URL and paste the request parameter.
6:29
Now, we need to set the API key
parameter equal to the API key
6:36
we obtained from GIPHY.
6:40
The API key I'm using will be disabled
once this course is published,
6:42
so be sure to paste your own API key here.
6:48
If you haven't requested
an API key from GIPHY,
6:53
please follow the instructions
steps right before this video.
6:55
I also posted a link to that instruction
step in the teachers notes below.
7:01
Let's add some more request parameters.
7:06
Let's tell GIPHY API that we only want
24 GIFs, and their rating should be G.
7:09
So in our fetch URL, let's add an and
7:16
symbol followed by limit, and
we'll set the limit to 24.
7:20
Now let's add the rating parameter and
set it equal to g.
7:26
The fetch API uses JavaScript
promises to handle results.
7:31
Promises let you chain methods
in a sequential order,
7:37
in other words, something happens
after something else is done.
7:41
For example, after the data is returned,
then convert that data to JSON.
7:47
The fetch method itself returns a promise,
and you can chain then methods as
7:54
callbacks that get executed sequentially
once the fetch promise is fulfilled.
7:59
In this case,
8:07
the promise is fulfilled when the browser
receives the data from the server.
8:07
So let's go ahead and
chain two then methods to fetch.
8:14
You can also place them on separate
lines to make your code easier to read.
8:22
Each of these callbacks use
the promise created by fetch to return
8:29
a promise of their own.
8:34
So next, we'll make the first callback
return the results in JSON format and
8:36
the second will update the GIFs state.
8:42
Once the data finishes loading,
fetch returns a response object
8:45
containing the response, and
we can access it in the callbacks.
8:50
So in the first then method, let's write
a function that takes the response
8:56
object and returns an object
containing the data in JSON format.
9:01
Once this promise is fulfilled,
9:08
we'll need to make the JSON data available
to the app by setting the state in React.
9:10
So in the second then method,
I'll update the gifs state by
9:17
passing in a function that takes
the JSON data via the parameter
9:22
responseData and
pass it to the setGifs function.
9:27
Now taking a look at the GIPHY API docs,
9:33
we see a sample success response for
the trending GIF endpoint.
9:36
We get an object with three properties,
data, pagination, and meta.
9:43
We can also see this if we
console.log the responseData.
9:49
Let's save our changes.
9:55
And notice how the console
logged the response data twice.
9:58
This is because the StrictMode tag's here.
10:02
In development, StrictMode causes React
to run the useEffect hook one extra time
10:06
before the component mounts to verify your
effect logic is implemented correctly.
10:11
Now back to the response data.
10:18
Notice this array of data containing an
object with all the properties of the GIF.
10:21
So we're gonna update the state with
the objects returned in this data array.
10:28
To access the data in this array,
we'll first undo the console.log,
10:34
and set the GIF state
to responseData.data.
10:40
Now, not all promises are fulfilled.
10:47
So if the fetch gets rejected or
returns in a failed state, for
10:50
example, if you're offline or
the API servers down,
10:55
you can use the catch method to catch and
handle any errors.
10:59
So let's chain the catch
method to the sequence.
11:06
Now catch will be used when we
get an error fetching the data.
11:12
We'll return an error message along with
the rejection reason as a console log.
11:16
So let's write an arrow function
that takes the parameter error.
11:23
We'll return a console log, with a
message, Error fetching and parsing data.
11:29
Then pass in the error.
11:40
All right, now let's test our app to make
sure we're bringing in the data correctly.
11:44
Over in the browser,
you don't see any GIFs yet,
11:50
we'll add the code to display
them in a later video.
11:54
But if you open up React DevTools and
inspect the app component,
11:58
you'll see the array of
objects fetched from the API.
12:02
Each object contains data about a GIF,
like its id, url, title, and more.
12:07
Great, now we know that the fetch
method is fetching the data and
12:16
updating state as expected.
12:21
Coming up in the next video,
you will learn about Axios,
12:24
a tool that's similar to to the Fetch API,
with useful built in features.
12:27
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