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

91
Views
Mutate parent array in child component

So I have the following array in my parent, which I fetch from an API:

[
  {
    "id": 1,
    "name": "Mars",
    "price": 2.99,
    "availableCount": 6
  },
  {
    "id": 2,
    "name": "Roshen",
    "price": 3,
    "availableCount": 14
  },
  {
    "id": 3,
    "name": "Kinder",
    "price": 2.99,
    "availableCount": 65
  },
]

And the parent component is this:

const Checkout = () => {
  const [productData, setProductData] = useState([]);

  useEffect(() => {
    Promise.resolve(getProducts()).then((result) => {
      setProductData(result);
    });
  },[]);

return (
  productData.map(product => {
    return <Product
      key={product.id}
      id={product.id}
      name={product.name}
      availableCount={product.availableCount}
      orderedQuantity={product.orderedQuantity}
      price={product.price}
      total={product.total}
    />
  })
  //further down, I calculate total price based on ordered products
)

};

The child component has the following definition:

const Product = ({ id, name, availableCount, price, orderedQuantity, total }) => {
  //need to be able to add or subtract orderedQuantity with user input in this component
}

My problem is, how would I go around incrementing and decrementing orderedQuantity without sending down the whole productData and the setProductData hook? Is there any way to mutate the parent array without specifically searching for that product in the productData and setting a new array with setProductData in the child component?

I need to mention that I need to calculate the total price of all ordered products in my parent component, so that's why I would like to have the right orderedQuantity in the productData.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Send the behavior as a callback to the child.

Minimal example of updating a parent with a list on state from a child:

const P = () => {
  const [l, setL] = useState([{id: 1, count: 10}]);
  const remove = id => setL(l.filter(e => e.id === id));
  const inc = id => setL(l.map(e => e.id === id ? ({...e, count: e.count+1}) : e));
  
  // remove={() => remove(e.id)} is the key bit
  return l.map(e => <C id={e.id} remove={() => remove(e.id)} inc={() => inc(id)} />); 
};

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!