0

What should I type in XXX if I want to check if there are any object in imagesWithChangedName with id which is same as the image ID?

 const [imagesWithChangedName,setImagesWithChangedName] = useState([])

 const handlePhotoNameChange = (e, imageID) =>{
    e.preventDefault()
    if(imageID && e.target.value){
        if(XXX === imageID)
            setImagesWithChangedName([...imagesWithChangedName,{id:imageID, changedName: (e.target.value) }])
        }
    }
 }

Edit: Also, How to replace the value of changedName value of with new value if XXX === imageID is equal to true?

2 Answers 2

1
 const [imagesWithChangedName,setImagesWithChangedName] = useState([])

 const handlePhotoNameChange = (e, imageID) =>{
    e.preventDefault()
    if(imageID && e.target.value){
        if(imagesWithChangedName.some(image => image.id === imageID)) {
          const indexToChange = imagesWithChangedName.reduce((acc, image, i) => image.id === imageID ? i : acc, 0);
          const mutableImages = [...imagesWithChangedName];

          mutableImages[indexToChange] = { id:imageID, changedName: (e.target.value) };

          setImagesWithChangedName(mutableImages);
        }
    }
 }

This will find your image and replace the correct value without adding an additional value to your array.

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

Comments

1

Replace your if(XXX === imageID) with:

if (imagesWithChangedName.find(img => img.id === imageID))

To replace the content:

if(imageID && e.target.value){
  const image = imagesWithChangedName.find(img => img.id === imageID);

  if (image) {
    image.changedName = e.target.value;
    setImagesWithChangedName(imagesWithChangedName);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.