I am learning to use hooks with react and trying to make a simple website where you write 2 values and add them to a list. Each item in the list got a delete button.
For some reason, when I am adding more than 2 rows the problem seems to start. If I for example add 2 rows, and press delete on the old rows that got loaded on start - it is either deleting them or replacing them with same values as the new rows.
Not sure what I am doing wrong here since the delete works until I add more than +2 rows directly at the start.
Kinda hard to explain, but I've made a sandbox where it's easier to see the problem.
Delete & add functions:
const deleteRow = async (index, e) => {
var data = testArr;
data.splice(index, 1);
setTestArr([...data]);
};
const addRow = async e => {
var obj = {
id: 1,
start: inputFrom,
stop: inputTo
};
var data = testArr;
data.push(obj);
setTestArr([...data]);
};
Mapping function:
{testArr.map((item, index) => (
<div key={item.id} className="col-12">
<div className="control-group mb-1">
<span className="mr-2">
{item.start} - {item.stop}
</span>
<input
type="button"
className="btn btn-light"
value="Delete row"
onClick={e => deleteRow(index, e)}
/>
</div>
</div>
))}
Sandbox: