I am attempting to convert the following function to be async in React (using CompressorJS):
const UploadImages = ({ jobInfo, setLoading, getData, accountInfo }) => {
    const [files, setFiles] = useState([]);
    const onDrop = useCallback( uploadedFiles => {
        uploadedFiles.forEach((file) => {
            console.log(file)
            new Compressor(file, {
                quality: 0.5,
                width: 500,
                height: 500,
                resize: "contain",function.
                success(result) {
                    setFiles([...files, result]);
                    console.log(result)
                },
                error(err) {
                    console.log(err.message);
                },
            });
        })
    }, [files]);
    return(<a bunch of stuff here>);
}
When using the snippet above, if uploadedFiles contains more than one file, there becomes an issue with compressing each photo and adding it to the state ([files, setFiles]). Only one of the images will be added and the others will be missed.
I have spent a number hours attempting to rework this function in different ways and the best solution I have come up with so far has been the following:
function compressFile(file) {
    return new Promise((resolve, reject) => {
        new Compressor(file, {
            quality: 0.5,
            width: 500,
            height: 500,
            resize: "contain",function.
            success(result) {
                resolve(result) 
            },
            error(err) {
                console.log(err.message);
                reject(err)
            },
        });
    });
}
function compressFiles(files) {
    return new Promise((resolve, reject) => {
        files.forEach((file) => {
            console.log(file)
            compressFile(file)
                .then(compFile => { 
                    console.log(compFile)
                    setFiles([...files, compFile]);
                })
        })
        resolve()
    })
}
const onDrop = useCallback( async acceptedFiles => {
    message.loading('Compressing Images...');
    compressFiles(acceptedFiles)
}, [files]);
Unfortunately, this still does not work and I was wondering if someone could explain where I am going wrong.
This should help:
const compressFiles = files => Promise.all(
  files.map(file => compressFile(file))
)
  .then(compressedFiles => {
    console.log(compressedFiles);
    setFiles([...files, ...compressedFiles]);
  });
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