Need help with a React Project

Hii everyone,
I made a React shopping cart app just for learning react-router and transfer of data and states from a component to another. However, I have a problem with one component that is the cart.jsx. I will provide the repository link as well as the live demo below. The problem is with calculating the total amount. I took different approaches but couldn’t solve it. Upon increasing the quantity of the items, the price of the objects was also being doubled. So If any one could check out the repository and let me know of possible fixes, that would be of great help.

Live Demo

Project Repository

The problem is in src/componentscart.jsx.

Also, the site is not responsive as of now.

I have some serious questions here.

First, calculateTotal seems to only take into account the items in the cart, not the quantitites.

In general, your cart component is very confusing - really that is 2-3 components stuck in the same file.

Next:

export function CreateComponentCard({ product, itemToDelete, itemQuantity }) {

    const [quantity, setQuantity] = useState(1);

Why is this component having its own quantity state? The calling component has quantities and needs to know and control them. I would be passing in the quantity and a callback to change them in the parent component.

Next, your cart is mapped thusly:

{filteredCart.map(createBillingDetails)}

filteredCart is a state variable.

You are passing them into this as billingDetailsbillingItem:

    function createBillingDetails(billingDetails) {
        return (
            <CreateBillingComponent billingItem={billingDetails} itemQuantity={itemQuantityState} key={billingDetails.id} />
        )
    }

You are then mutating that object:

export function CreateBillingComponent({ billingItem, itemQuantity }) {

    if (itemQuantity.id === billingItem.id && itemQuantity.operation === "increase") {
        billingItem.quantity = (itemQuantity.quantity) + 1;

How is React going to know that that data has changed? You can’t mutate state. Repeat it 1000 times, you can’t mutate state. Every time you mutate state, Dan Abramov strangles a puppy. You have to replace the state with a new object so React can tell that it has changed. Since this is a state variable, you need to do that with the setFilteredCart function or there is no guarantee that React will understand.

I would want to fix those things before moving on.

2 Likes

Thank you, for taking out time and giving a detailed reply.
And yes, completely agree with that. I have only used useState hook in this project that led to so many workarounds.
However, right now am learning useContect and useReducer for easy state management. Will update the links once I complete it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.