3 - Fetching Data
Recap
Last week we looked at using props and state to create React components that change with user input (interactive example):
Fetching Data in React
Often when you create a React app, you will want to fetch data from an API and display it inside your components. How do we do this in React?
You might think that we could just fetch the data in the component like this, but unfortunately it won't work (interactive example):
Danger This code won't work!
This is because React is synchronous, while fetch
is asynchronous. If we look in the console, we'll see that the imgSrc
will always be null
when we try to render it. React will try to render before fetch
has had time to get the data from the API.
We need a way of running the fetch
call after we have rendered for the first time, so that it is not racing against React updating the DOM. Then once we have got the data back we can use state to tell React to re-render with the new data.
The way we do this is with another Hook, provided by React. This one is called useEffect
.
Importing useEffect
useEffect
Just like useState
, we will import useEffect
into our file like this (interactive example):
If we look in the console, we'll see that useEffect
is also a function like useState
.
Often, we will need to use useState
and useEffect
together. They are imported together like this:
Using useEffect
useEffect
Now let's look at how to use the useEffect
Hook (interactive example):
The useEffect
Hook takes two arguments:
A callback function, where we can put our
fetch
call. In this example, we're fetching some data from the NASA API!An array, which we'll look at later but is very important that you don't forget it!
Tip : When writing your useEffect
, write the "skeleton" first, then fill in the callback function later.
You might have noticed that we still haven't rendered the data from the API. We now need to tell React to re-render once we get the data. This sounds like a job for state!
Let's look an example of how we can use state and useEffect
to do this (interactive example):
The timeline of this component is now what we wanted at the start:
The component renders for the first time. Notice that we are returning
null
here: if a component returnsnull
, then React will render nothing on-screenAfter rendering, the
useEffect
callback is run, so it fetches data from the NASA APIWhen the response is received, we update the state
This causes a re-render so that we can show the data on-screen
You might notice that even though we re-rendered, we did not run the useEffect
a second time. The way we've set it up, useEffect
will only run after the first time a component renders. We'll look at controlling this in more detail later.
Exercise A (estimate: 15 min) |
1. Open the |
2. Create a new file |
3. Render the |
4. Take a few minutes to read the code in the new |
5. Create a new state variable called |
6. Now add a |
7. Inside the |
8. Add a |
9. Add a second |
11. Within the second |
12. Still within the second |
13. What happens in your browser? Do you understand why? If not, discuss it with another student. If you are both stuck, ask a Teaching Assistant. |
Conditional rendering
In the MartianPhotoFetcher
component above, we wrapped our JSX inside an if
/ else
statement. This is common practice in React, as it allows us to show something different depending on the situation (for example if there is no data to display, show the user something else instead).
You may also see this done in 2 other ways:
The ternary operator ? :
The ternary operator follows this structure condition ? outputIfTrue : outputIfFalse
(interactive example):
The double ampersand &&
The double ampersand &&
is used when you don't have an else
. The implication is that when the condition is not fulfilled, nothing will render (interactive example):
You'll notice in the &&
example above, we do not render a 'Loading...' message, because there is no alternative output (no else
case).
Exercise B (estimate: 5 min) |
1. Open the |
2. Change the |
The Circle of Life
We now know how to fetch data and render it in our React applications. However, there was a problem with the method that just learned. To understand this problem we first have to understand the lifecycle of a component.
Let's take a look at an example:
Exercise C (estimate: 10 min) |
1. Open this CodeSandbox. |
2. Take 5 minutes to read the code. |
3. Click the "Fetch image for 2019" button. If you're feeling confident: predict what is going to happen before you click the button. |
4. Now click the "Fetch image for 2020" button. What did you expect to happen? What actually happened? Can you explain why? |
Together let's "play computer" to break down exactly what is happening with these components:
When the page loads, the
App
function component is calledIt doesn't have any
date
state already, so we initialize it to an empty string (""
) withuseState
It renders the 2 buttons, but because
date
is an empty string, it does not render theMartianImageFetcher
component. Insteadnull
is returned, which means that nothing is rendered
When we click the "Fetch image for 2019" button, the
handle2019Click
click handler is calledThe state is set by
setDate
to be"2019-01-01"
, and a re-render is triggeredThe
App
function component is called againThis time,
useState
remembers that we havedate
state and it is set to"2019-01-01"
Now
App
does renderMartianImageFetcher
and passes thedate
state as a prop namedphotoDate
The
MartianImageFetcher
function component is called for the first timeuseState
knows that we haven't got anyimgSrc
state so initializes it tonull
We queue an effect, which will run after we render for the first time
Because the
imgSrc
state is set tonull
, we returnnull
. This means that nothing is rendered
Now that the component has rendered for the first time, the effect is run
A
fetch
request is made to the NASA APIWhen the request data comes back, we set the
imgSrc
state to a piece of the data, which triggers a re-render
The
MartianImageFetcher
function component is called againuseState
remembers that theimgSrc
state is set to the data from the APIThis time, we do not queue an effect. We set up
useEffect
with an empty array ([]
), which means that we only run after the first renderWe do have
imgSrc
state set, so we render the image using the data from the API
Phew! That was a lot of work just to render an image! But we're not quite done yet, we still need to find out what happens when we click the "Fetch image for 2020" button:
In the
App
component, thehandle2020Click
click handler is calledThe
date
state is set to"2020-01-01"
and a re-render is triggeredThe
App
function component is called again and thedate
state is set to"2020-01-01"
The
date
prop that is passed toMartianImageFetcher
is different which means that it has to re-render
In the
MartianImageFetcher
componentuseState
remembers that we already hadimgSrc
state. It is set to the image from 2019Again, we do not queue the effect because this is a re-render and
useEffect
has been passed an empty array[]
Because
imgSrc
state has been set previously we render the image from 2019
Exercise D (estimate: 5 min) |
1. Did you spot where the bug was? Discuss with a group of 2 - 3 students where you think the bug is. |
2. Report back to the rest of the class where you think the bug happened. |
HINT : The key that the useEffect
in MartianImageFetcher
is only run once. This is because we told React that the queue should be queued on the first render only. However, as we saw, sometimes you need the effect to run again when some data changes. In this case the date
prop, changed from "2019-01-01"
to "2020-01-01"
, meaning that we have to fetch data different data. We call this a dependency of the effect. Any variables which are used inside the useEffect
callback function are dependencies.
useEffect
dependencies array
useEffect
dependencies arrayTo solve this problem, we can tell React to queue the effect on the first render and when a dependency changes. We do this by adding the dependency variable to the array (interactive example):
Now when the photoDate
prop changes, React knows that the effect must be run again, this time with the 2020 date. Because of this behavior, the second argument to useEffect
is called the dependencies argument. We use it whenever we have something in our effect function that depends on a variable outside of the effect function.
Here's a diagram showing when the useEffect
callback will be run:
To help you understand this better, try "playing computer" again, but this time think about what happens when we use [props.photoDate]
for the dependencies argument. Think carefully about what changes with step 6 after we click the 2020 button.
Exercise E (estimate: 10 min) |
1. Open the |
2. Create a new file |
3. Open |
4. Take a few minutes to read what the |
5. Open the |
6. Open your browser and find where the |
7. Refresh the page. What happens now if you click the "Fetch Bulbasaur" button, then click the "Fetch Charmander" button? Is this what you expected? Discuss with another student why this happens. |
8. Fix the bug by adding |
ESLint rules for React Hooks
As you may have noticed, VSCode highlighted the empty dependencies array when you changed the URL passed to fetch
in PokemonMoves
.
This is because your React application is using the rules from eslint-plugin-react-hooks
, a package created by the developers who make React. It helps you to find bugs in React Hooks code by highlighting places where you might be missing dependencies.
If you see a red squiggly line underneath your useEffect
dependencies array, you can hover your mouse over and it will tell you which variable is missing so you can add it to the dependencies array. Here's an example:
Working with forms in React
Modern web applications often involve interacting with forms such as creating an account, adding a blog post or posting a comment. This would involve using inputs, buttons and various form elements and being able to get the values entered by users to do something with it (like display them on a page or send them in a POST request). So, how do we do this in React?
Controlled component pattern
A popular pattern for building forms and collect user data is the controlled component pattern. A pattern is a repeated solution to a problem that is useful in multiple similar cases. Let's have a look at an example (interactive example):
We're controlling the value
of the input by using the value from the reminder
state. This means that we can only change the value by updating the state.
It is done using the onChange
attribute and the handleChange
function which is called every time the input value changes (typically when a new character is added or removed).
If we didn't call setReminder
in the handleChange
function, then the input's value would never change and it would appear as if you couldn't type in the input! Finally, the value we keep in the reminder
state is displayed on the screen as today's reminder.
In addition, instead of just saving the value of the input in the state, we could have also transformed the string before we set it with setReminder
, for example by calling toUpperCase()
on the string.
Exercise F (estimate: 10 min) |
1. Open the |
2. Create a new file |
3. Open the |
4. Take a few minutes to understand what the |
5. Add an |
6. Set the |
7. Create a function within the component called |
8. Change the |
9. Add a |
10. Using |
Form with Multiple Fields
Let's have a look at a more complex example where we want to build a form to let users enter information to create a personal account (interactive example):
We now have three different inputs named username
, email
and password
. There is a corresponding state variable and change handler function for each value.
Exercise G (estimate: 10 min) |
1. Open the |
2. Render an |
3. Create a new state variable called |
4. Add a |
5. Create a new |
6. Add a |
7. Add a parameter called |
8. Change the |
9. Open your browser, type a Pokémon name into the |
10. Empty the |
11: (STRETCH GOAL) Make sure the user cannot add a Pokémon to the |
Inlining event handlers
We could make our code a bit shorter if we inlined our event handlers (interactive example):
Centralizing event handlers
Sometimes we need to put all of our update logic in one function, maybe because we need to validate the user's input before we set it in state.
We can use a single handleChange
function, that is reused to keep track of changes for all of the form fields. To be able to tell which <input>
is being updated, we check the event.target.name
field. This corresponds to the name
attribute on the <input>
(e.g. <input name="username">
).
Based on this value, we then decide which state to update (interactive example):
Form submission
So far, our form examples don't have a way of sending the user data back to the server, so that we can store it in the database.
We will be using a special submit
event triggered on the <form>
element. This event is triggered when the user clicks a submit button or if they hit the Enter key. Let's take a look at an example (interactive example):
We set up our <form>
to handle the event by passing the handleSubmit
function to the onSubmit
prop. If we click on the Submit button or hit Enter while focused on the form, the event is triggered and the handleSubmit
function is called.
The first thing we do inside the handler function is call event.preventDefault()
. This is necessary because the browser has a default action when the submit event is triggered on the form to send a GET request to the server. We prevent the default action because we will handle the event ourselves.
We can then do whatever we want with our user data! In this example, we're sending a POST request using the fetch
method.
Further Reading
Container components
There is a common pattern when loading data in React applications, called container components.
Multiple fields as state pattern
There is another common pattern for handling multiple fields in a form, but it requires some JavaScript functionality that you may not have seen before.
Homework
If you haven't already, complete the in-class exercises on your
pokedex
appComplete all of the lesson 3 exercises in the cyf-hotel-react project.
Try to complete the Stretch Goal exercises in the cyf-hotel-react homework
Last updated