I would like to send post request after every 10 count (ie. i = 10) (Slice 10 array of object from ImageObject and send it to backend). But i cant seem to update the state.
eg. if my ImageObject length === 500 , after every 10 loop , slice 10 array from ImageObject and send it to backend and so on untill ImageObject === 0
import { useState } from "react";
import axios from "axios";
import { v4 as uuidv4 } from "uuid";
import { S3Client } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";
type ImageType = {
name: string;
};
export default function App() {
const [mediaPath, setMediaPath] = useState<ImageType[]>([]);
const [file, setFile] = useState<File[]>([]);
const handleImagePaths = async (paths: ImageType[]) => {
try {
const options = {
headers: {
"Content-Type": "application/json"
}
};
await axios.post(
`/api/folders/uploads`,
{
media: paths
},
options
);
} catch (error) {
console.error(error);
}
};
const handleUpload = async () => {
for (var i = 0; i < file.length; i++) {
const imgFile = file[i];
// aws-sdk upload
const id = uuidv4();
const path = `folder/${imgFile.name}`;
let ImageObject: ImageType[] = [];
for (let j = 0; j < file.length; j++) {
ImageObject.push({
name: file[j].name
});
}
setMediaPath(ImageObject);
if (i % 10 === 0) {
const paths = ImageObject.slice(0, 10);
handleImagePaths(paths);
}
const target = {
Bucket: process.env.REACT_APP_HOST_AWS_BUCKET,
Key: path,
Body: imgFile,
ContentType: "image/jpeg"
};
const creds = {
accessKeyId: process.env.REACT_APP_HOST_AWS_ACCESS_KEY_ID || "",
secretAccessKey: process.env.REACT_APP_HOST_AWS_SECRET_ACCESS_KEY || ""
};
try {
const parallelUploads3 = new Upload({
client: new S3Client({
region: process.env.REACT_APP_HOST_AWS_DEFAULT_REGION || "",
credentials: creds
}),
leavePartsOnError: true,
partSize: 1024 * 1024 * 1000,
params: target
});
parallelUploads3.on("httpUploadProgress", (progress: any) => {});
await parallelUploads3.done();
} catch (e) {
console.error(e);
}
}
};
return (
<div className="App">
<h1>Send Post API After every 10 loop</h1>
</div>
);
}
Help !!