Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using setState with an array of objects

I am having a state with two products like this:

const [product, setProduct] = useState([
    {
      name: 'Hat',
      description: 'Nice cartoon hat',
      images: [
        'linktoimage',
      ],
      amount: 799,
      currency: 'eur',
      quantity: 0,
    },
    {
      name: 'Gift',
      description: 'Nice cartoon gift',
      images: [
        'linktoimage',
      ],
      amount: 599,
      currency: 'eur',
      quantity: 0,
    },
  ]);

I want to display them so I use a regular mapping :

<div className='product'>
        {product.map((p) => (
          <div>
            <h3>{p.name}</h3>
            <h4>
              Stripe Amount:{' '}
              {(p.amount / 100).toLocaleString('en-US', {
                style: 'currency',
                currency: 'EUR',
              })}
            </h4>
            <img src={p.images[0]} width='250px' alt='product' />
           
            <span style={{ margin: '20px', fontSize: '2em' }}>
              {p.quantity}
            </span>

            <button
              className='btn btn-sm btn-success'
              onClick={() => {
          
                setProduct([...p, (p.quantity = Math.max(0, p.quantity + 1))]);
              }}
            >
              +
            </button>
          </div>
        ))}

I am having hard time changing the quantity ( my last button) all I want is to change the products quantity but i cant do it somehow

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

tried like this:

  onClick={() => {setProduct([...p, (p.quantity = Math.max(0, p.quantity + 1))]);
}}

says that p is not iterable, i did another thing but when I inceremented my other product disappeared , i guess it is because I set the productState to …p .

How can I incerement the given p product without losing my other product in my state?

>Solution :

This is a way you can do to update the quantity of element:

...
{product.map((p, indx) => (
...
          <button
              className='btn btn-sm btn-success'
              onClick={() => {
                  const updateProducts = product
                  updateProducts[indx].quantity += 1
                  setProduct([...updateProducts])
              }}
            >
              +
         </button>
}}
))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading