Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
Add same product with different color and price to the cart

Now I can only add products using one price. In db I have two prices and different colors. It needs to work like this, the first price is applied to the first color, the second price to all others colors

/src/app.js

const {getData} = require('./db/db');
const products = getData();
const [cartItems, setCartItems] = useState([]);

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}])
    }
  };

/src/components/cart.jsx

function Cart({cartItems, onCheckout}) {
    const totalPrice = cartItems.reduce((a, c) => a + c.price[0] * c.qty, 0);
    return (
        <div className='cart_container'>
            <br/>
            <Button
                title={`${cartItems.length === 0 ? "Cart is empty" : "Cart" + '\n' + "Total Price: " + totalPrice} `}
                type={"checkout"}
                disable={cartItems.length === 0 ? true : false}
                onClick={onCheckout}
            />
        </div>
    );
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you can go about doing it this way :

const firstColor = "grey" // for example 
const totalPrice = cartItems.reduce((a, c) =>{
 const price = c.color == firstColor ? c.price[0] : c.price[1]
 return a + price * c.qty : 
}, 0);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!