Acquiring Data in React with useState
Let's acquire data with react in this lesson.
We'll cover the following
Now we are going to get our React page to also interact with the server. When last we left our React page in Dynamic Styled Components, it was displaying the seating information for one specific concert. What we’d like it to do now is get that seating information from the server and update it if it changes. This will use the fetch
method we’ve already seen, as well as a React hook called useState
that we first saw in the React chapter.
Updating the seating information involves adding the following features to the page:
- When the React components load, they need to get the current seating status from the server.
- The status needs to get passed down from the Venue component to the seat component that uses the status to display. In this chapter, we’re going to keep the status in our component. Later on, in the Managing State in React, we’ll look at how we can keep the status in a central global repository.
- We need to make sure a user can’t adjust a seat that is already sold. This is a UI bit we didn’t do when we were working on this page earlier.
- When the user does click on a seat, adding it to the shopping cart, we want the page to update the server so that any other user looking at the page sees the updated status.
That’s a lot, but most of it is similar to React features we’ve already used. Also, note that I am kind-of hand-waving over authentication issues at this point; our React code is not going to be very concerned about who actually holds each seat.
Let’s look at the new React parts first. Once that’s done, we need to add a couple of new Rails controller actions, but I’ll talk about them after we see how the React code works. We have a hierarchy of components here—Venue
to VenueBody
to Row
to Seat
—and they all change at least a little bit.
The venue
component
The Venue
component fetches the data from the server so that each individual Seat
component isn’t making its own data request. To acquire this data when the component renders, we need something analogous to the Stimulus connect
method, which is automatically invoked when the component is added. We can do that in React using a hook called useEffect
.
Here’s the entire Venue
component:
Get hands-on with 1200+ tech skills courses.