I have created a todo list app I can add or remove elements in that list I am using react state for this purpose. Adding new element is perfectly working but removal isn't whenever I click on remove it just remove everything except the last item I have added I am using removeItem method to perform this functionality and I am filtering that clicked value and map rest of values in this function and I have tried to print those values in console ad well and I am getting desired output in console but those values are not getting stored in state array and I don't know why its happening:
import { useState } from 'react';
import './App.css';
let App = ()=>{
const [initial, addInitial] = useState('');
const [val, addVal] = useState([]);
let changeHandler = (e)=>{
addInitial(e.target.value)
}
let addItem =(event)=>{
let newItem = initial;
addVal( (prevValues) => [...prevValues, newItem]);
}
let removeItem = (par)=>{
val.map((value, index)=>{
if(index != par){
addVal([ [...value] ])
}else{
}
})
}
return(
<div id="parent">
<div id="container">
<h1>To-Do List</h1>
<div id="sub1">
<input type="text" value={initial} onChange ={changeHandler} placeholder='Add a item' autoFocus/>
<button id="add" onClick = {addItem}>+</button>
</div>
<div id="sub2">
{
val.map((name, index)=>{
return(
<div id="cross" key={index}>
<button className="remove" id={index} onClick = { ()=> removeItem(index)}>❌</button>
{name}
</div>
)})
}
</div>
</div>
</div>
)
}
export default App;