const handleFileChange = async (e) => {
const target = e?.target?.files;
const attachments = await Array.from(target).reduce(async (acum, file) => {
file.id = uniqid();
// const format = file.name.split('.').pop();
// if (IMAGE_FORMATS.includes(format)) {
setIsLoading(true);
if (file.type.startsWith('image/')) {
const response = await channel.sendImage(file);
file.src = response.file;
acum.images.push(file);
} else {
const response = await channel.sendFile(file);
file.src = response.file;
acum.files.push(file);
}
setIsLoading(false);
return acum;
}, Promise.resolve({ files: [], images: [] }));
setFilesList(prev => {
console.log('files', [...prev, ...attachments.files]);
return [...prev, ...attachments.files];
});
setImagesList(prev => {
console.log('images', [...prev, ...attachments.images]);
return [...prev, ...attachments.images];
});
};
In the above code I got the following error
It looks it's cause by my initialization of array, but how should I address it?
async/awaitandPromise.resolve()it should work as expectedasyncandawaits?Promise.resolve()returns a Promise. So actually you are not passing{ files: [] ...}as initial value but a Promise. And a promise doesn't have afilesproperty ...Array.reduceisn't aware of async functions and doesn't await or handle them. You can build a promise chain with it though:.reduce((a, f) => a.then(... => f), Promise.resolve()).reduceover a simple loop? Doesn't seem like it's any simpler.