This video is available to students only

Fetching Single Product

In this lesson, we're going to fetch single product

Fetching single product#

Now we have some courses in our state already, so we can avoid going to the api requesting for the same data if it already exists. There can be situations where the user directly goes to the description page and we don't have the course in the state. We can centralize this call as well.

First of all, let's go to the courseSlice and create another thunk function for fetching the individual course. Rather than writing the whole code again, we can simply copy the one above and make some changes. Firstly, we need to call it getCourseAsync rather than calling it getCoursesAsync. This is going to return just the course, so we can delete paginated. Also, this time, we have the argument courseId of type string. We can change the type prefix to getCourseAsync and pass the courseId. The request is going to be getById with courseId as parameter. And this is it.

Let's write our add cases now. Like always, I will copy that and paste it here. For the first case, I can just change the prefix name to getCourseAsync. For the second case, I will use coursesAdapter.upsertOne because this call will add the particular course to the existing courses list. Status can stay the same. Finally, let's copy the third case and simply change courses to course.

We are now ready to see this in action. Let's get rid of the local state and use appSelector and this time, we will use coursesSelector.selectById. We will pass the state and the id we have here. Now inside the useEffect hook, we can check if there's no course. We can then dispatch the getCourseAsync request which will upsert the course value to the existing courses list.

Start a new discussion. All notification go to the author.