Quiero enviar un formulario que envíe una solicitud al servidor automáticamente.
Así es como cargo los archivos en el estado:
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); }; Estoy cargando 2 archivos en CSVFilesState ambos en el formulario.
Quiero activar la solicitud cuando ambos archivos estén en el estado. ¿Cómo puedo esperar los archivos y solo luego enviar la solicitud?
Esta es mi función onSubmit -
const onSubmit = (event: React.FormEvent) => { event.preventDefault(); backendAPIAxios .post("/", CSVFilesState) .then((response: AxiosResponse<IServerResponseData>) => { }) .catch((e: AxiosError) => { }); };Intenté hacer eso (no funcionó) -
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])Verificó el conteo de CSVFilesState.