Home > front end >  How to calculate a specific product item's initial price from a shopping cart functionality in
How to calculate a specific product item's initial price from a shopping cart functionality in

Time:09-26

Issue: I am stuck in terms of how to calculate a product item's initial price when its quantity is going to be increased or decreased.

Problem: The calculation for the initial price of a product merges the other prices of the other products, thus making it become as a subtotal for all of the products' prices

All throughout the calculation logic, it uses props and useStates to handle an object data (data.jsx). In terms of rendering the products, it would use "mapping" to scan the object data file.

Now, when we calculate the initial price, it would use .reduce() function which involves an accumulator and a current value. This is where I get very confused since I literally don't have an idea on how to limit out the calculation of the initial price of a certain specific product item only. Currently, the initial price calculates all of the product items prices instead of focusing to only one.

Initial Prices

Source code for the basket.jsx (includes the calculation):

import React from "react";

export default function Basket(props) {
  const { cartItems, onAdd, onRemove } = props;

  const itemsPrice = cartItems.reduce((a, c) => a   c.price * c.qty, 0);
  
  // const specificItemPrice = cartItems.reduce((a, c) => a   c.price * c.qty, 0);  
  // (how to change the logic of this condition to limit it only with one product rather than merging the prices of other products)

  const totalPrice = itemsPrice; //stuck here, itemsPrice became total price
  // const totalPrice = itemsPrice   specificItemPrice; commented out since I am not sure

  return (
    <aside className="block col-1">
      <h2>Cart Items</h2>

      {/* Display message when cartItemsLength is 0 */}
      <div>{cartItems.length === 0 && <div>Cart is Empty</div>} </div>

      {/* Renders the added item to the basket of the shopping cart through mapping cartItems */}
      {cartItems.map((item) => (
        <div key={item.id} className="row">
          <div className="col-2">
            {item.name} -- ${item.price.toFixed(2)}
          </div>

          {/* Increment and Decrement Buttons */}
          <div className="col-2">
            <button onClick={() => onRemove(item)} className="remove">
              -
            </button>
            <button onClick={() => onAdd(item)} className="add">
               
            </button>
            Qty: {item.qty}
          </div>

             {/* Intitial Price for product item -------------------PROBLEM HERE */}
          <div className="col-2 text-right">${itemsPrice.toFixed(2)}</div>
        </div>
      ))}



      {cartItems.length !== 0 && (
        <>
          <hr></hr>

          <div className="row">
            <div className="col-2">
              <strong>Total Price</strong>
            </div>
            <div className="col-1 text-right">
              <strong>${totalPrice.toFixed(2)}</strong>
            </div>
          </div>
          <hr />
          <div className="row">
            <button onClick={() => alert("Implement Checkout!")}>
              Checkout
            </button>
          </div>
        </>
      )}
    </aside>
  );
}

Source code for the App.jsx (includes the increment and decrement functionality)

import Header from "./components/Header";
import Main from "./components/Main";
import Basket from "./components/Basket";
import data from "./data";
import { useState } from "react";

function App() {
  const { products } = data;
  const [cartItems, setCartItems] = useState([]);

  // -------------Add and Remove product functionality------------------------------------------
  const onAdd = (product) => {
    const exist = cartItems.find((x) => x.id === product.id);
    if (exist) {
      setCartItems(
        cartItems.map((x) =>
          x.id === product.id ? { ...exist, qty: exist.qty   1 } : x
        )
      );
    } else {
      setCartItems([...cartItems, { ...product, qty: 1 }]);
    }
  };

  const onRemove = (product) => {
    const exist = cartItems.find((x) => x.id === product.id);
    if (exist.qty === 1) {
      setCartItems(cartItems.filter((x) => x.id !== product.id));
    } else {
      setCartItems(
        cartItems.map((x) =>
          x.id === product.id ? { ...exist, qty: exist.qty - 1 } : x
        )
      );
    }
  };
  // -------------------------------------------------------------------------------------------

  return (
    <div className="App">
      <Header />

      <div className="row">
        <Main onAdd={onAdd} products={products} />
        <Basket
          onAdd={onAdd}
          onRemove={onRemove}
          cartItems={cartItems}
        ></Basket>
      </div>
    </div>
  );
}

export default App;

Full source codes in CodeSandBox (functioning App):

https://codesandbox.io/s/initialpricefixing-cherry-h0br4o-h0br4o?file=/src/components/Basket.jsx

Possible solution: I might want to replace the {itemsPrice.toFixed(2)} with {item.price.toFixed(2) * c.qty} where c.qty represents the respective item and item.price also represents the respective item. But still I am confused on how to pull this off since "c" may become undefined.

Clearly, I based this App from a YouTube video by Coding with Basir, I just modified it a little bit to make the calculation of the product items more simpler. Video link: https://www.youtube.com/watch?v=AmIdY1Eb8tY

Your responses would indeed help me out a lot since I am very much confused right on how to handle the "cartItems" in calculating the product item's initial price. Thank you very much!!!

CodePudding user response:

Hey just change line 40 in your Basket.jsx to this:

<div className="col-2 text-right">${(item.price*item.qty).toFixed(2)}</div>
  • Related