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

144
Views
Change a single product quantity using state (react)

So ,I wanted to change this one product object in the UI with a button click, and reduce the quantity of the product. But the quantity amount did not change .What is the best move in situations like that.

let product={ a:1,b:2,c:3}; 

Lets say changing the value.

b:5; 
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

please check this sample code

import React, { useState, useEffect } from 'react';

export default function App() {
  const [products, setProducts] = useState([
    { name: 'Product 1', qty: 1, price: 10 },
    { name: 'Product 2', qty: 1, price: 20 },
  ]);

  const [totalAmt, setTotalAmt] = useState(0);

  useEffect(() => {
    const total = products.reduce((s, i) => s += i.price * i.qty, 0);
    setTotalAmt(total);
  }, [products]);

  const incrQty = (index) => {
    setProducts((v) => {
    const a = JSON.parse(JSON.stringify(v)); // FOR AVOIDING MUTATING DATA, BECAUSE IN STRICT MODE THIS SETSTATE CALLBACK WILL TRIGGER TWICE
      a[index].qty += 1;      
      return [...a];
    });
  };

  const decrQty = (index) => {
    setProducts((v) => {
    const a = JSON.parse(JSON.stringify(v));
      a[index].qty -= 1;      
      return [...a];
    });
  };

  return (
    <div>
      Total Amount: Rs.{totalAmt}
      <ul>
        {products.map((e, k) => (
          <li key={k}>
            {e.name}, qty={e.qty}, subtotal {e.qty * e.price},
            <button onClick={e => incrQty(k)}>Incr Qty</button>
            {
              (e.qty > 1)?<button onClick={e => decrQty(k)}>Decr Qty</button>:null
            }
          </li>
        ))}
      </ul>
    </div>
  );
}
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!