I want to submit a form that send a request to server automatically.
This is how I load the files into the state -
const onUpload = (event: ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
const id = event.target.id;
const fileReader = new FileReader();
const file = event.target.files![0];
fileReader.onload = () => {
setCSVFilesState([...CSVFilesState, { id, file: fileReader.result }]);
};
fileReader.readAsDataURL(file);
};
I'm uploading 2 files to the CSVFilesState both in the form.
I want to fire the request when both files are in the state. How can I wait for the files and only then send the request?
This is my onSubmit function -
const onSubmit = (event: React.FormEvent) => {
event.preventDefault();
backendAPIAxios
.post("/", CSVFilesState)
.then((response: AxiosResponse<IServerResponseData>) => {
})
.catch((e: AxiosError) => {
});
};
Tried to do that (didn't work) -
const onUpload = (event: ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
const id = event.target.id;
const fileReader = new FileReader();
const file = event.target.files![0];
fileReader.onload = () => {
setCSVFilesState([...CSVFilesState, { id, file: fileReader.result }]);
};
fileReader.readAsDataURL(file);
if (CSVFilesState.length === 1) onSubmit(event);
};
useEffect(()=>{
if(CSVFilesState.length === 2){
onSubmit()
}
},[CSVFilesState])
Checked the count of CSVFilesState.