How can I call the axios when the user clicks the submit button?
Unable to add an onclick event handler on the submit button, where shall I declare the onClick event function which calls axios or accepts acceptedFiles variable in this code.
useCallback is called when the user drops files, and files get automatically uploaded when the user drops the files. I want files to be uploaded when the user clicks submit button.
import React, {useCallback, Component} from 'react';
import {useDropzone} from 'react-dropzone';
import axios from 'axios';
function Basic(props) {
const onDrop = useCallback(acceptedFiles => {
let formData = new FormData();
for (var i = 0; i < acceptedFiles.length; i++) {
let file = acceptedFiles[i];
formData.append('articleFiles[]', file);
}
axios({
method: 'post',
data: formData,
)}
}, [])
const {acceptedFiles, getRootProps, getInputProps} = useDropzone({onDrop});
const files = acceptedFiles.map(file => (
<li key={file.path}>
{file.path}
- {file.size}
bytes
</li>
));
return (
<section className="container">
<div {...getRootProps({className: 'dropzone'})}>
<input {...getInputProps()}/>
<p>Drag 'n' drop some files here, or click to select files</p>
</div>
{files.length > 0 && <React.Fragment>
<div>
<h4>Files</h4>
<ul>{files}</ul>
</div>
<button>Submit</button> //<---
</React.Fragment>}
</section>
);
}
export class UploadManuscript extends Component {
render() {
return (<Basic/>)
}
}
export default UploadManuscript
I have done it:
import React, {Component} from 'react';
import {useDropzone} from 'react-dropzone';
import axios from 'axios'
function Basic(props) {
const uploadFiles = () => {
let formData = new FormData();
for (var i = 0; i < acceptedFiles.length; i++) {
let file = acceptedFiles[i];
formData.append('articleFiles[]', file);
}
axios({
method: 'post',
data: formData,
})
}
const {acceptedFiles, getRootProps, getInputProps} = useDropzone();
console.log(props.id)
const files = acceptedFiles.map(file => (
<li key={file.path}>
{file.path}
- {file.size}
bytes
</li>
));
return (
<section className="container">
<div {...getRootProps({className: 'dropzone'})}>
<input {...getInputProps()}/>
<p>Drag 'n' drop some files here, or click to select files</p>
</div>
{files.length > 0 && <React.Fragment>
<div>
<h4>Files</h4>
<ul>{files}</ul>
</div>
<button onClick={uploadFiles}>Submit</button>
</React.Fragment>}
</section>
);
}
export class UploadManuscript extends Component {
render() {
return (<Basic/>)
}
}
export default UploadManuscript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With