State Management with React Context 3 exercises

Integrating User Reviews and Ratings into a Product Detail Page

As a starting point, the CartContext with initial state has been copied into the 04-complete-react-state directory.

Let's explore how to manage user-generated reviews and dynamically update average ratings in our app.

Current State of Reviews in the Application

When visiting a product page

Loading exercise


00:00 So I've copied our CART context with initial state application into a complete React state directory ahead of our going and figuring out how to do reviews. So let's go take a look at our reviews currently in the application. So when you take a look at any of these products, including this cool dragon T-shirt,

00:17 you'll see a set of reviews. You can add your own reviews simply by typing your review in here, awesome shirt, as well as setting the rating and then submitting the review. Now, two things are going to happen. One, it's going to add that review and it's also going to update the average rating located right above the add to CART.

00:37 So now let's go take a look at our code. The code for this starts over in the products ID route in the page RSC where we get the product detail component. It takes an ID and then we get the product information by that ID. Now, let's go take a look at that product information because that's an interesting mix of both immutable and mutable data.

00:56 So we take a look at our types of a product type. It's got the ID, the image, name, price, and description. All of that is static and immutable data, and then it's got the list of reviews, which is going to be mutable data, and that has a rating and a text for each review.

01:12 So this RSC is going to show that immutable data, the name, the image, the price, and so on, and then it's going to use client components to manage the reviews. Those client components include the average ratings component. That's the one that takes the reviews and then gives you

01:30 a current average rating. It also includes the reviews component that not only shows the reviews, it also allows you to add a review by typing in some text, which it stores as local state, and then sends the server using the add review action. That add review action is defined in the parent RSC and then passed

01:48 down into that reviews client component. Again, we're going to do this via React context and state. If you have any questions, be sure to refer to that resources section associated with this video. Good luck.