Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing item from array in useState()

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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=()=>{

}

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading