G
G
gooseNjuice()2022-04-07 09:21:08
JavaScript
gooseNjuice(), 2022-04-07 09:21:08

What does it take for the code to run in the correct sequence?

I don't understand asynchrony yet. What needs to be done so that the code in useEffect is correctly substituted into the body of the formData request? In the console, I first get the res output, then the getAnalyzedAppData function prints data is undefined , and only then does the blob appear in the console and passed successfully

useEffect
useEffect(() => {
        console.log('useEffect strated')
        if (location.state && location.state.apk) {
            updSpinner(true);
            const fileUploaded = usePassFile(location.state.package, location.state.apk);
            console.log('fileUploaded', fileUploaded)
            const fileName = fileUploaded.name;
            const appSize = setCorrectSize(fileUploaded.size);
            const formData = new FormData();
            formData.append('file', fileUploaded);

            try {
                const res = async () => await axios({
                    method: 'post',
                    url: 'api/admin/parse',
                    data: formData,
                    headers: {'Content-Type': 'multipart/form-data'},
                });
                console.log(res)
                getAnalyzedAppData(res.data, appSize, fileName, fileUploaded, false);
                updSpinner(false);
            } catch (error) {
                console.log(error);
                updSpinner(false);
            }
        }
    }, []);

usePassFile
const usePassFile = async (name, url) => {
    console.log('usePassFile')
    try {
        const blob =  (await fetch(apkURL(url)).catch(e=>console.error(e))).blob();
        console.log('blob', blob)
        const dt = new DataTransfer();
        dt.items.add(new File([blob], name, {type: blob.type}));
        console.log('passed successfully:', dt);
        return dt.items[0]
    } catch (err) {
        console.error('the file wasn\'t passed:');
        console.error(err);
    }
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2022-04-07
@gooseNjuice

IMHO, for starters, throw out React. Then - Axios. And practice on some JSFiddle . Try promises, async/await, display a couple of things with jsonplaceholder. When you understand how asynchrony works, you can easily integrate it into your react and in general to any other place, and until the end of your professional activity you will not have plugs on the basics of asynchrony in JavaScript.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question