Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  22] [ 3]  / answers: 1 / hits: 136031  / 6 Years ago, wed, october 31, 2018, 12:00:00

I've been running through a react file upload tutorial and want to add on to it. I'm trying to make it so when a user clicks the upload message the browser will prompt them saying Your file is being uploaded I'm not a frontend dev by any means so please forgive me if this question is super nooby. For some reason when I use this code, if you navigate to the web page the code in the function runs once, and then again on click. My intended use is to only run on click, any idea what I am doing wrong?



import React, { Component } from 'react'
import { Alert } from 'react-alert'

class Main extends React.Component {
constructor(props) {
super(props);

this.state = {
imageURL: '',
};

this.handleUploadImage = this.handleUploadImage.bind(this);
}

handleUploadImage(ev) {
ev.preventDefault();

const data = new FormData();
data.append('file', this.uploadInput.files[0]);
data.append('filename', this.fileName.value);

fetch('http://localhost:8000/upload', {
method: 'POST',
body: data,
}).then((response) => {
response.json().then((body) => {
this.setState({ imageURL: `http://localhost:8000/${body.file}` });
});
});
}

render() {
return (
<form onSubmit={this.handleUploadImage}>
<div>
<input ref={(ref) => { this.uploadInput = ref; }} type=file />
</div>
<div>
<input ref={(ref) => { this.fileName = ref; }} type=text placeholder=Enter the desired name of file />
</div>
<br />
<div>
<button onclick=myFunction()>Upload</button>
<script>
function myFunction() {
alert(Your file is being uploaded!)
}
</script>

</div>
<img src={this.state.imageURL} alt=img />
</form>
);
}
}

export default Main;

More From » node.js

 Answers
10

Why don't you move the alert at the begining of handleUploadImage function?



handleUploadImage(ev) {
alert(Your file is being uploaded!)
....
}


and instead of



<div>
<button onclick=myFunction()>Upload</button>
<script>
function myFunction() {
alert(Your file is being uploaded!)
}
</script>

</div>


you will have



<div>
<button type=submit>Upload</button>
</div>

[#53197] Monday, October 29, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacie

Total Points: 476
Total Questions: 92
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Tue, Mar 29, 2022
2 Years ago
stacie questions
Fri, Jun 26, 20, 00:00, 4 Years ago
Thu, Jan 23, 20, 00:00, 4 Years ago
Fri, Aug 30, 19, 00:00, 5 Years ago
Fri, Aug 2, 19, 00:00, 5 Years ago
;