0

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) […] ]
1
  • 1
    setObject(objects => objects.concat(images)) is one way. Commented Mar 19, 2024 at 2:12

1 Answer 1

2

Instead of pushing:

setObject([...objects, ...images])

Or even better (and more recommended way - functional update form):

setObject((prev) => [...prev, ...images])
// `prev` here takes the previous value of the `object` state

And when you are filtering something, use !== instead, it would be more accurate. Read more about it here

Sign up to request clarification or add additional context in comments.

8 Comments

See Why React useState with functional update form is needed? for why this isn't exactly a good idea
Functional update form is not always needed unless you came across certain cases, like when you're updating the same state multiple times in one go. In his example, he's not doing that, so the answer I gave would be fine. I definitely don't think it deserves a downvote as it is not a wrong answer. It just depends on the use case?
You should ALWAYS use the functional update form when you are setting a state variable to a value based on its current value. The code pattern setFoo(foo+1) or setFoo(foo.push(...)) should make your skin crawl.
@Owenn What worked for me was setObject([...prev, [...images]])
@Neptunas I believe what you meant is setObject((prev) => [...prev, ...images])?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.