Home > Back-end >  Removing item from array in useState()
Removing item from array in useState()

Time:05-29

I am learning react. Need some help to understand this.

I have two buttons. One "add random text" other is "remove".

For the add button I've used Math.random to generate number and added some text with that.

I want to show the list items by mapping it. And when the remove button is clicked the last item will be removed.

I tried pop() but that only shows the removed one. How can i keep the whole list and just remove last one?

const [data, setData]=useState([]);
let addHandler =()=>{
//Newdata is Math.random()*100 some text
setData([...data, newdata])
}
let removeHandler=()=>{

}

CodePudding user response:

One way to do this is you could use .slice() to partition your array from 0 to length - 1

let removeHandler=()=>{
    setData(data.slice(0, data.length - 1))
}

.pop() should work as well. E.g.

data.pop() // removes last element from array
setData([...data]) // clone remaining array
  • Related