Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS - onChange triggering twice

Tags:

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?

like image 619
James Lock Avatar asked Nov 26 '18 11:11

James Lock


1 Answers

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

like image 199
Dory Daniel Avatar answered Oct 04 '22 23:10

Dory Daniel