am tried to list my products details in table with check box, then i need to get some product id with is going to checked
Here my code
const [products, setProducts] = React.useState([]);
const preload = async () => {
const data = await getAllActiveProducts();
const loadedproducts = [];
for(const key in data){
loadedproducts.push({
id: key,
pid: data[key]._id,
name: data[key].name,
price: data[key].price,
inventory: data[key].inventory,
image: data[key].image
})
}
console.log(loadedproducts);
setProducts(loadedproducts);
}
React.useEffect(() => {
preload();
}, []);
const productsList = products.map(product =>
<ActiveProductItem
key = {product.id}
id = {product.pid}
name = {product.name}
description = {product.description}
price = {product.price}
SKU = {product.SKU}
inventory = {product.inventory}
image = {product.image}
productStatus = {product.productStatus}
/>);
ActiveProductItem code is here
const ActiveProductItem = (props) => {
const { name, price, SKU, inventory, image, id, key} = props;
const [selectedProducts, setSelectedProducts] = React.useState([]);
return (
<tbody>
<tr>
<td><input type="checkbox" onClick={(event) =>{
const checkedproducts = selectedProducts;
if (event.target.checked) {
const value = event.target.value;
console.log(value);
checkedproducts.push({id});
setSelectedProducts([
...selectedProducts,
{
id: id
},
]);
}else {
// remove from list
setSelectedProducts(
selectedProducts.filter((product) => product.id !== id),
);
}
console.log(selectedProducts);
console.log(checkedproducts);
}} name="prod-item" value={id}/></td>
<td><span class="admin-list-img"><img src={`${API}/${image}`} alt="" /></span></td>
<td>
<div class="">
<a href="edit-product.html"><u>{name}</u></a>
</div>
<span>SKU: <span>{SKU}</span></span>
</td>
<td>${price}</td>
<td>{inventory}</td>
</tr>
</tbody>
);
};
UPDATED
const productsList = products.map(product =>
<ActiveProductItem
key = {product.id}
id = {product.pid}
name = {product.name}
description = {product.description}
price = {product.price}
SKU = {product.SKU}
inventory = {product.inventory}
image = {product.image}
productStatus = {product.productStatus}
handler = {checkHandler}
/>);
I tried both array push method and set state too but result always show the single id which checked the last
Please tell me what i did wrong , am very very new to reactjs Thank you