I am creating the list from the skidList array and handling copy and delete operation on each skid as well as on click of delete button I am calling deleteSkid
method which removes skid at that index and updates the list.
However, Instead of deleting skid at a particular index, it deletes the last skid in the array list.
const CreateNewTab = () => {
const [skidList, setSkidList] = useState([]);
const [productNameMap, setproductNameMap] = useState({});
useEffect(() => {
let skidList = [];
let newSkid = {};
newSkid["2"] = "0";
newSkid["3"] = "0";
newSkid["4"] = "0";
skidList.push(newSkid);
setSkidList([...skidList]);
let productNameMap = {};
productNameMap["2"] = "PEN";
productNameMap["3"] = "PENCIL";
productNameMap["4"] = "ERASER";
setproductNameMap({ ...productNameMap });
}, []);
const updateProductQuantity = (skid, key, newQuantity, index) => {
console.log("Inside update Skid Quantity Index= " + index);
skid[key] = newQuantity;
let newSkidList = skidList;
newSkidList.splice(index, 1, skid);
console.log(newSkidList);
setSkidList([...newSkidList]);
};
const deleteSkid = (index) => {
console.log(index);
let newSkidList = skidList;
newSkidList.splice(index, 1);
console.log("Skid deleted from: " + newSkidList);
setSkidList([...newSkidList]);
};
const insertSkid = (skid) => {
setSkidList(skidList.concat([{ ...skid }]));
};
return (
<div>
{skidList.flatMap((skid, index) => (
<div style={{ marginRight: "0", paddingRight: "0" }}>
<Row style={{ margin: "0", padding: "0" }}>
<Col span={19}>
{Object.keys(skid).map((key) => (
<Row>
<Col span={16}>
<h6>{productNameMap[key.toString()]}</h6>
</Col>
<Col span={8}>
<InputNumber
min={0}
defaultValue={skid[key]}
rules={[
{
required: true,
message: "Please input quantity!",
},
]}
onChange={(newQuantity) => {
updateProductQuantity(skid, key, newQuantity, index);
}}
/>
</Col>
</Row>
))}
</Col>
<Col span={5}>
<Row>
<Col span={12}>
<Button
type="primary"
icon={<CopyOutlined />}
size="large"
shape="circle"
onClick={() => insertSkid(skid)}
/>
</Col>
<Col spna={12}>
<Button
type="primary"
size="large"
shape="circle"
danger
icon={<DeleteOutlined />}
onClick={() => deleteSkid(index)}
/>
</Col>
</Row>
}
</Col>
</Row>
<Divider />
</div>
))}
</div>
);
};