1

I have an array of products like this:

products = [
 {id: 'x1c', name: 'p1', quantity: 4},
 {id: 'cd1x', name: 'p2', quantity: 4},
 // more products ...
]

render products:

products.map(product => {
  return <input value={product.quantity} />
});

How I can make state and can handle change a quantity of a product independent?

0

2 Answers 2

2

You could store an object with key-value pairs of productId-productQuantity

const products = [
  { id: 'x1c', name: 'p1', quantity: 4 },
  { id: 'cd1x', name: 'p2', quantity: 4 }
]

const [productQuantity, setProductQuantity] = useState(
  products.reduce(
    (obj, product) => ({ ...obj, [product.id]: product.quantity }),
    {}
  )
)

products.map(product => {
  return (
    <input
      value={productQuantity[product.id]}
      onChange={e =>
        setProductQuantity({ ...productQuantity, [product.id]: e.target.value })
      }
    />
  )
})

Codesandbox for demo

Edit zealous-lalande-hhcdb

Sign up to request clarification or add additional context in comments.

Comments

0

I dont know if i get you right but..

Set products in state

Const [product,setProduct] = useState({
    products:[
      {id: 'x1c', name: 'p1', quantity: 4},
      {id: 'cd1x', name: 'p2', quantity: 4},
      // more products ...
   ]
})

**List products **

function list(){
  product.products.map(product => 
   Return <p id={product.id}>{product.quantity}</p>
  )
}

In render

return ({list})

So if you add another product to array which is in state ,it should render it automatically.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.