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
http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC
Resources
- Giphy API documentation
- Fetch API – MDN
- Introduction to fetch()
- Browser support for fetch()
- fetch() polyfill
- Browser support for JavaScript promises
Treehouse React Courses and Workshops
[MUSIC]
0:00
Hey everyone, Guil here, a front-end web
development teacher here at Treehouse.
0:04
In this workshop, I'll teach you a couple
of different ways to fetch external
0:08
data with React and
how to display the data in your app.
0:12
We're going to create this
fun GIF searching app
0:15
using the Giphy API from giphy.com.
0:18
A GIF search engine where users
can search for reaction GIFs.
0:21
So I'm gonna assume that you know
the basics of React like creating and
0:25
rendering components, passing props
to components and managing state.
0:29
If you're not sure what this means,
be sure to check the teacher's notes for
0:33
links to Treehouse courses and workshops
that will get you up to speed with React.
0:36
To code along with me, download
the project files for this workshop and
0:40
open them in your favorite text editor.
0:43
I'm using Atom.
0:45
In your terminal or console, navigate
to the gif-search project folder and
0:47
run npm install to install
the project dependencies.
0:53
Then npm start to run
the app in the browser.
0:58
So by now you know that
React is just a view library
1:02
that simply renders components using
the state and properties passed to them.
1:05
React itself doesn't have a built
in way to fetch data from a server.
1:08
In fact, since React's only
concern is rendering views,
1:12
it doesn't even know
that there is a server.
1:15
So there are several
JavaScript methods and
1:17
tools you can use to fetch
data in a React app.
1:19
The two methods I'll cover in
this workshop are the Fetch API,
1:21
a data fetching interface
that's native to the browser.
1:24
And axios, a popular tool that's similar
to Fetch with a few key differences and
1:28
advantages.
1:32
Both of these are Promised-based
approaches meaning
1:33
they use JavaScript Promises to handle
the results we get back from the server.
1:36
And you can learn a whole lot more
about JavaScript Promises by watching
1:41
the treehouse workshop I
posted in the teacher's notes.
1:44
In the app, we'll write all of our
data fetching code here in app.js.
1:47
This app component is the main
container of the app,
1:51
it's responsible for rendering the child
components of the app like a list of GIFs.
1:55
And it's going to pass them
the external data state via props.
2:00
So the first thing we'll do is define
an initial state inside a class.
2:05
I already have a constructor set up to
initialize state and calling super here.
2:10
Lets us use the keyword this inside the
constructor within the context of the App
2:14
class rather than the parent component
class we're extending from React.
2:19
So now in the constructor, we can write
this.state and set it equal to an object.
2:24
Now the state in our app is going to
be the GIF data we want to display.
2:30
So let's call the state gifs and
set it to an empty array by default.
2:34
So the gif state now represents a
collection of objects that will change and
2:38
be updated by components.
2:43
Next, right below the constructor,
we're going to set up
2:45
all of our data fetching inside React's
componentDidMount lifecycle method.
2:49
ComponentDidMount is called immediately
after a component is added to the d DOM.
2:59
So if you need to load external data right
when a component gets mounted to the DOM.
3:03
This is a good place to create the request
because at this point in the lifecycle,
3:07
the component has a DOM representation.
3:11
So inside componentDidMount,
3:14
we'll add the fetch method to start
the process of fetching our data.
3:16
Now fetch provides a simple way to
make web requests in the browser and
3:20
handle responses.
3:24
And in the fetch method,
we define the path or
3:25
URL to the resource we wanna
fetch in our case, the Giphy API.
3:28
And the Giphy API is open to the public
and they provide a public beta key
3:31
to let you try it out and the key is
required for all the API endpoints.
3:36
You can check out all the different
endpoints here in the Giphy API docs.
3:40
For this example, I'm going to return
data from the trending GIFs endpoint.
3:43
So I'll simply copy this URL from
the docs which also contains the public
3:48
key and
pass it to the fetch method as a string.
3:54
The fetch API uses JavaScript
promises to handle results,
3:58
the promises let you chain
methods in a sequential order.
4:02
In other words, something happens
after something else is done.
4:06
For example, after the data is returned
then convert that data to JSON.
4:09
So the fetch method itself returns a
promise and you can chain then methods as
4:14
call backs that get executed sequentially
once the fetch promise is fulfilled.
4:19
In this case, the promise is fulfilled
when the browser receives the data
4:23
from the server.
4:27
So I'll go ahead and
chain two then methods to fetch.
4:28
And you could also place them on
separate lines just to make your code
4:33
easier to read.
4:36
So each of these call backs use
the promise created by fetch to return
4:41
a promise of their own.
4:46
So next we'll make the first callback,
return the result in JSON format and
4:48
the second we'll update the gif state.
4:53
So once the data finishes loading,
fetch returns a response object
4:55
containing the response and
we can access it in the callbacks.
5:00
So in the first then method, I'll write
a function that takes the response object
5:04
and returns an object containing
the data in JSON format.
5:09
Once this promise is fulfilled,
5:13
we'll need to make the JSON data available
to the app by setting the state in React.
5:14
So in the second then method, I'll update
the gif state by passing in a function
5:19
that takes the JSON data via
the parameter responseData and
5:24
returns a new state with this.setState.
5:29
Then inside the parentheses,
we'll set gifs to responseData.
5:33
Now looking at the Giphy API docs,
we see a sample response for
5:41
the trending GIFS endpoint.
5:46
And in the response,
5:47
notice this array of data containing an
object with all the properties of a GIF.
5:49
So we're going to update the state with
the objects return in the data array.
5:54
To access the data in the array, we'll
set the gif state to responseData.data.
5:58
Now not all promises are fulfilled,
so the fetch gets rejected or
6:05
returns in a failed state.
6:09
For example, if you're offline or
the API server is down,
6:11
you can use the catch method to catch and
handle any errors.
6:14
So let's change the catch
method to the sequence and
6:18
now catch will be used when we
get an error fetching the data.
6:22
We'll return an error message along with
the rejection reason as a console log.
6:27
So let's write an error function
that takes the parameter error.
6:32
We'll return a consul log with
the message Error fetching and
6:41
parsing data, then pass in the error.
6:47
All right, now let's test our app in
the console to make sure we're bringing in
6:55
the data correctly.
6:59
So in the render method,
lets log the gif state,
7:00
console.log(this.state.gifs),
7:03
I'll give this a save.
7:13
And over in the browser,
you won't see any gifs yet.
7:15
We'll add a code to display
them in a later video.
7:18
But if you open up the console, you'll see
the array of objects fetched from the API.
7:20
Each object contains data about a gif
like its URL, ID, size and more.
7:25
And if you inspect the app
component in React dev tools,
7:31
you'll see that the gif state now
consists of the array of 25 objects.
7:34
So great, now we know that the fetch
method is fetching the data and
7:38
updating state as expected.
7:42
The fetch method and
7:44
JavaScript Promises are available in
the latest generation of most browsers.
7:45
So to make sure that your data fetching
also works in older browsers, as well as
7:50
all modern browsers, you can install
the fetch polyfill developed by GitHub.
7:54
I've posted the link in the teacher's
notes along with up to date
7:59
information on browser support for
fetch and promises.
8:02
So coming up in the next video,
you'll learn about axios.
8:05
A tool that similar to the fetch
API with better browser support and
8:09
useful built in features.
8:13
You need to sign up for Treehouse in order to download course files.
Sign up