So i have an ecommerce app which which for a product, i want customers to post different variants of the product with the quantity and price for the variant. Then on save, I want the product to be save based on the number of variants.
For instance if there are 3 variants of the product, the product should be saved 3 times with same name and description, but each save would have a single variant.
Here's what i have done.
const [values, setValues] = useState([])
function addItem(e) {
e.preventDefault()
setValues([...values, { quantity, weight, price }])
setQuantity('')
setWeight('')
setPrice('')
}
<input
type='text'
placeholder='Product Name*'
value={productName}
onChange={(e) => setProductName(e.target.value)}
/>
<div className='form-group'>
<input
type='number'
placeholder='Quantity'
value={quantity}
name={quantity}
onChange={(e) => setQuantity(e.target.value)}
/>
<input
type='number'
placeholder='Weight (kg)'
value={weight}
name={weight}
onChange={(e) => setWeight(e.target.value)}
/>
<input
type='number'
placeholder='Price'
value={price}
name={price}
onChange={(e) => setPrice(e.target.value)}
/>
<button onClick={addItem}>Add</button>
</div>
OnClick, the item is added to a state. Then onSubmit, i try to loop through the state
for (let i = 0; i < values.length; i++) {
const res = await createProduct({
productName,
price: price[i],
quantity: quantity[i],
weight: weight[i],
})
console.log(res)
}
It doesn't work
Here's the express controller
exports.createProduct = async (req, res) => {
try {
const newProduct = await Product.create(req.body)
res.json(newProduct)
} catch(err) {
console.log(err)
}
}
Try to change your React onClick function:
for (let i = 0; i < values.length; i++) {
const { price, quantity, weight } = values[i];
const res = await createProduct({ productName, price, quantity, weight })
console.log(res)
}