James Lock
James Lock

Reputation: 185

React JS - onChange triggering twice

When I upload an image using react-image-uploader the onchange triggers twice. so it attempts to upload the image to the backend twice, here is how I handle it:

//user uploads image to app
<ImageUploader
   buttonClassName={"btn add-btn bg-orange"}
   buttonText='ADD'
   onChange={this.newProfilePicture}
   imgExtension={['.jpg', '.gif', '.png', '.gif']}
   maxFileSize={5242880}
   fileSizeError="file size is too big"
   fileTypeError="this file type is not supported"
   singleImage={true}
   withPreview={true}
   label={""}
   withIcon={false}
/>



 //image is set to this.userprofilepicture
    newProfilePicture = (picture) => {
    this.setState({ userprofilepicture: picture});
    this.setNewProfilePicture();
    ShowAll();
}

//new profilepicture is uploaded to api
setNewProfilePicture = () => {
    let data = new FormData();
    console.log('profile picture: ', this.state.userprofilepicture)
    data.append('Key', 'profilePicture');
    data.append('Value', this.state.userprofilepicture)
    this.sendUpdatedPicture('uploadprofilepicture', data);
}

Is there a way to get this to only trigger once?

Upvotes: 5

Views: 4238

Answers (2)

Dory Daniel
Dory Daniel

Reputation: 826

if you are using create-react-app then your Appcomponent is wrapped in StrictMode like this:

<React.StrictMode>
  <App />
</React.StrictMode>,

go to index.js and remove <React.StrictMode></React.StrictMode>

https://github.com/facebook/react/issues/12856#issuecomment-390206425

Upvotes: 4

Satyaki
Satyaki

Reputation: 751

<ImageUploader
   buttonClassName={"btn add-btn bg-orange"}
   buttonText='ADD'
   onChange={event => this.newProfilePicture(event)}
   imgExtension={['.jpg', '.gif', '.png', '.gif']}
   maxFileSize={5242880}
   fileSizeError="file size is too big"
   fileTypeError="this file type is not supported"
   singleImage={true}
   withPreview={true}
   label={""}
   withIcon={false}
/>

and in the function,

newProfilePicture = event => {
  event.preventDefault();
  event.stopPropagation();
  ...your code...
}

This should solve your issue, here we are stopping the event to be propagated to the next level. So that onChange executes only once.

Upvotes: 0

Related Questions