I am trying to develop a component that has two columns: one from which you can add something to a list, and the other one in which you can see/modify items which are already added. I wanted to create a function that deletes the element from the list using splice(index, 1), however, it was always deleting elements from an index to the end. I started debugging it, and I have a problem that I cannot solve. I pass a function as a prop that is suppose to log all elements in a state of a parent component.
Here is my code:
const ElementCreator = () => {
const [elements, setElements] = useState([]);
const addElement = () => {
const elementsSlice = elements.slice();
const newElement = (
<Example
position={elements.length}
deleteHandler={handleElementDelete}
key={elements.length}
/>
);
elementsSlice.push(newElement);
setElements(elementsSlice);
};
const handleElementDelete = (position) => {
console.log(elements);
};
return (
<Row>
<Col>
<Button onClick={addElement}>Add Example Element</Button>
</Col>
<Col>
<div>{elements}</div>
<Button
onClick={() => {
setElements([]);
}}
>
Reset
</Button>
</Col>
</Row>
);
};
const Example = (props) => {
return (
<div>
{props.position}
<div>
<Input type="checkbox" />
<Input type="checkbox" />
<Input type="checkbox" />
</div>
<div>
<Button
onClick={() => {
props.deleteHandler(props.position);
}}
>
Delete
</Button>
<Button>Move Up</Button>
<Button>Move down</Button>
</div>
</div>
);
};
Anytime I press the delete button, I get a different results. Here is how the console output looks like when I press each button:
[]
react_devtools_backend.js:4049 [{…}]
react_devtools_backend.js:4049 (2) [{…}, {…}]
react_devtools_backend.js:4049 (3) [{…}, {…}, {…}]
react_devtools_backend.js:4049 (4) [{…}, {…}, {…}, {…}]
Can someone tell me why logging the same thing yields different result in each case?
There are a couple issues with this code..
#1 you are assigning a variable to an array with an empty slice called on it (this could introduce bugs, and not sure why you would need to call this empty function)
#2 you are passing the length of the array, then you are wanting to delete something based on the position variable that is tied to the length of that array.
Array length != the last index of an array
arr = [0,1,2,3] => arr has a length of 4, but if you called arr[4] you would get undefined
You say you are clicking on the add button, your function is doing exactly what it is supposed to be doing => adding an element to your current elements state array.
const addElement = () => {
const elementsSlice = elements.slice();
const newElement = (
<Example
position={elements.length}
deleteHandler={handleElementDelete}
key={elements.length}
/>
);
elementsSlice.push(newElement);
setElements(elementsSlice);
};