Page F.P.T
Page F.P.T

Reputation: 671

react images upload how to update state array during onchange

I am new at react and I am creating an upload images functionality using this: https://github.com/JakeHartnell/react-images-upload as a guide.

however i am having issues with the set state, it adds the file even if i removed it from the upload

enter image description here

As you can see in the screenshot, i have added two photos, removed one and added one again. when i checked the state. it has 6 files in the array. how do i fix this one?

this is my onchange function:

 onDrop = picture => {
      this.setState({
        artistGallery: this.state.artistGallery.concat(picture),
      });
  };

i am calling it here:

 <ImageUploader
     withIcon={true}
     buttonText='Choose images'
     onChange={this.onDrop}
     imgExtension={['.jpg', '.gif', '.png', '.gif']}
     maxFileSize={5242880}
     withPreview={true}
 />

Upvotes: 2

Views: 887

Answers (1)

Upasana
Upasana

Reputation: 1975

Your 'onDrop' function is getting called on 'add' as well as on 'remove' action. And you are concatinating the image files entries in onDrop thats why images entries are duplicated on each call.

In your case assuming 'picture' is the array of images, Change your onDrop function to this:

onDrop = picture => {
      this.setState({
        artistGallery: picture
      });
};

Please note: I have tried this using the link you have provided in your question with react-images-upload. Hope it helps!

P.S. I have raised a pull request on the source you have used.

Upvotes: 2

Related Questions