I have a Question. For example, I have a State like this:
const [data,setData] = useState([{
name:'',
email:''
}])
Now Somehow I have to update the index of the object by using onChange
Is this the right approach?:
const handleAddChange = (e)=>{
setData((prev)=>(prev[index]={
...prev[index],
[e.target.name]:e.target.value
})
}
You can say use a temp value for this kind of operation. But I want to know, can I update the state index directly without using any temp variable?
Since ES2023 you can use Array.toSpliced()
, which works like Array.spliced()
, but returns a new array:
const handleAddChange = e => {
setData(prev =>
prev.toSpliced(i, 1, {
...prev[i],
[e.target.name]: e.target.value
})
)
}
Original answer:
Use Array.map()
to iterate the array and update the matching index:
const handleAddChange = e => {
setData(prev =>
prev.map((o, i) => i === index
? { ...o, [e.target.name]: e.target.value }
: o
)
)
}