Search code examples
reactjsreact-hooksmern

How array of object update in React.useState?


const [products, setProducts] = useState([
    {
      price: 999,
      title: "Watch",
      qty: 1,
      id: 1,
      img: "https://media.istockphoto.com/photos/military-style-watch-picture-id650233226?s=612x612",
    },
    {
      price: 20000,
      title: "Samsung F42",
      qty: 1,
      id: 2,
      img: "https://images.samsung.com/is/image/samsung/p6pim/in/sm-e426bzahins/gallery/in-galaxy-f42-5g-8gb-ram-sm-e426bzahins-514504593?$684_547_PNG$",
    }]);

I want to update the qty by onClick and passing this data from component 1 to component 3 via component 2. So, what will be the statement for setProducts to update the qty.


Solution

  • pass this function with parameter Id as callback to onClick

    function increaseQuantity(Id){
      let res = products.map((obj) => obj.id === Id ? {...obj,qty:obj.qty+ 1} : obj)
      setProducts(res);
    }
    

    example -

    <button onClick={() => increaseQuantity(item.id)}></button>