This video is available to students only

Refactoring and Adding Basket Items Count

In this lesson, we're going to refactor the basket page and display the basket items count in the header

Refactoring and adding Basket items count#

Now that we have centralized the state, we don't want to individually call basket items inside our Basket page. We can simply import the basket and use it here. Inside useEffect hook, we can simply remove everything and use the newData function with the imported basket. Also inside the dependency, we will pass basket.

Since we are here, we can import removeItem from the useStoreContext as well, and inside the removeBasketItem function, we can chain the removeItem function and pass the courseId. Now I want to show the basket items count in the header as well, so let's go to the Navigation file and import basket from useStoreContext. We want to show just the count of the basket items, so we can create a new const called basketCount and it will simply be equal to basket.Items.Length. We can now pass the basketCount inside the span. And I don't want to show zero as basket items so we can use ternary operator which will render it only when basketCount is more than zero.

Let's style our cart now. Below the search class, paste the code I have provided. I have positioned the cart to be relative and the count with position: absolute, color white and background color to be the primary color of our application.

Let's wrap the basket icon with Link so that the user can go to the basket page if they click on this. Let's wrap the class with link and the to property will be /basket. When we click on add to cart, we want it to make it appear in the count above, right away. Let's go the ShowCourses component and import setBasket from the context, and inside addToCart method, I can chain it with setItem and pass the response to it. This will centralize the data. I also want to show Add to Cart if the product is not inside already; otherwise, we can link it to the cart.

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