Hello, I am making Website OS in React.js, and I have bug with arrays. Can you help me?
array code:
const [openedWindows, setOpenedWindows] = useState([
]);
const handleWindowAdd = () => {
setOpenedWindows([...openedWindows, { openedWindow: "" }]);
}
const handleWindowRemove = (index) => {
const list = [...openedWindows];
const i = openedWindows.indexOf(index);
list.shift(i, 1);
setOpenedWindows(list);
//alert(index);
}
Github Repository: https://github.com/Retr0A/creative-os
Thank you if you help!
I want to remove item from array in handleWindowRemove
, but it removes all other items.
CodePudding user response:
I think you are looking for Array.prototype.splice
.
Array.shift
removes the first item of an array.
Here is a corrected example:
const [openedWindows, setOpenedWindows] = useState([
]);
const handleWindowAdd = () => {
setOpenedWindows([...openedWindows, { openedWindow: "" }]);
}
const handleWindowRemove = (index) => {
const list = [...openedWindows];
const i = openedWindows.indexOf(index);
list.splice(i, 1);
setOpenedWindows(list);
//alert(index);
}
CodePudding user response:
Shift method is supposed to remove the first element of the array and does not take any arguments. You could use the splice method instead.
However, I find filter method works best here:
const handleWindowRemove = (index) => {
const updatedList = openedWindows.filter((el, idx) => idx !== index);
setOpenedWindows(updatedList);
}