I'm new to React and I want to keep track of array: images, as it changes. I'm using useState and I want to add array of objects into another array. I can accomplish this with push(), but based on React documentation, this is mutating the array, which is not the right way. How could I accomplish this using array spread ..., slice() etc?
Code
const [images, setImages] = useState(data.images)
const [prev, setPrev] = useState([])
const removeImage = (image) => {
prev.push(images)
setImages(images.filter(i => i.id != image.id))
}
Result
Array(1) [ (5) […] ]
Array(2) [ (5) […], (4) […] ]
Array(3) [ (5) […], (4) […], (3) […] ]
setObject(objects => objects.concat(images))is one way.