'Delete an element from an array - React JS
Im making a table of materials that, when i press the delete button a material have to disappear and im using the splice() method but when i push the delete button of the first element, this action deletes all the elements of the array.
Here is the function that apparently make this happen but isn't working :(
RemoveMaterial = (material_id) => {
let element = [...this.state.material_list];
const material = element.findIndex((item) => item === material_id);
const list = [...this.state.material_list];
const consumption_list = [...this.state.material_consumption];
const material_list = [...this.state.materials];
list.splice(material)
consumption_list.splice(material)
material_list.splice(material)
this.setState({
material_list: list,
material_consumption: consumption_list,
materials: material_list,
});
};
Solution 1:[1]
Try this:
RemoveMaterial = (material_id) => {
//...
const list = [...this.state.material_list];
list.splice(material,1);
this.setState({
material_list: list
});
//...
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | M K |
