Home > OS >  How to replace the value of an array item which is prop of a parent object, by using useState?
How to replace the value of an array item which is prop of a parent object, by using useState?

Time:12-11

I am trying to make image upload inputs by preview, whose count is for example 5, I mean there are 5 " " buttons which will be used to upload images.

For 5 box, I am showing below the code with Array(5). I have an object:

const [object, setObject] = useState[{
    name: "",
    imageUrls: Array(5)
  }]

When the 3rd array item of imageUrls array changes, I want to update this object this way:

setObject({...object, imageUrls: object.imageUrls[2] = "xxx"})   // doesn't work

Also tried this way but again giving syntax errors.

setObject({...object, imageUrls[2]: "xxx"})   // doesn't work

What is the correct way of doing this and writing the right syntax? Thanks in advance.

CodePudding user response:

You could try the following: Access the previous state snapshot, copy the object into a new reference, update the desired field, and return the new object.

setObject((prevState) => {
   copy = {...prevState};
   copy.imageUrls[2] = "xxx";
   return copy;
})
  • Related