react-use-cart component. How to calculate the total price

Viewed 716

the npm package I am using

Hello All! I am trying to implement a cart for a simple website that fetches from an API. So my render method looks something like this...

{somedata.map((items) => {
        return (
          <div key={items._id} className="col-md-3 col-12 my-2">
            <div className="card h-100">
              <button
                className="btn btn-light"
                onClick={() => addItem(items)}
              >
                Add to Cart
              </button>

              <img className="card-img-top" src={items.photo.url} alt="" />
              <div className="card-body text-center">
                <h3 className="card-title m-2">{items.title}</h3>
                <p className="card-text">{items.description}</p>
                <span className="card-text border p-3 m-2">
                  <b>CAD {items.price} $</b>
                </span>
              </div>
            </div>
          </div>
        );
      })}

And this is what my cart looks like. I am just using the example they provided us.

return (
  <>
    <div className="row cart_box">
      <h1>Cart ({totalUniqueItems})</h1>

      <ul className="cart_ul">
        {items.map((item) => (
          <li key={item.id} className="cart_li">
            {item.quantity} x {item.title}
            <div>
              <img
                className="img-fluid"
                src={item.photo.url}
                width="100px"
                alt=""
              />
            </div>
            <button
              className="btn btn-info"
              onClick={() => updateItemQuantity(item.id, item.quantity - 1)}
            >
              -
            </button>
            <button
              className="btn btn-info"
              onClick={() => updateItemQuantity(item.id, item.quantity + 1)}
            >
              +
            </button>
            <button
              className="btn btn-info"
              onClick={() => removeItem(item.id)}
            >
              &times;
            </button>
          </li>
        ))}
       </ul>
    </div>
   </>
   );
   }

My question is now How do I implement the total price? I do see a carttotal method there but I couldn't figure out how to implement this. Any help is appreciated thanks! :)

1 Answers

Seems cartTotal is just a value representing the total value in the cart. It's not a function from what I can tell.

You can see by the state interface it's a number:

interface InitialState {
  id: string;
  items: Item[];
  isEmpty: boolean;
  totalItems: number;
  totalUniqueItems: number;
  cartTotal: number; // <-- number type
  metadata?: Metadata;
}

Initial state object:

export const initialState: any = {
  items: [],
  isEmpty: true,
  totalItems: 0,
  totalUniqueItems: 0,
  cartTotal: 0, // <-- number value
  metadata: {},
};

It computes the total value as implemented here:

const calculateTotal = (items: Item[]) =>
  items.reduce((total, item) => total + item.quantity! * item.price, 0);

You should be able to destructure cartTotal from the useCart hook's return object.

const { cartTotal } = useCart();

...

<div>Cart total: {cartTotal}</div>

If cartTotal isn't working for you then you can also manually compute the cart total yourself using the same computation over the items array you are already rendering.

Related