ow to Trigger Download After Form Submission in React?

I have a React application where I need to trigger a download after successfully submitting a form. I have a handleDownloadClick function that handles the download process. My goal is to call this function once the form submission is complete and successful.

Home.js

<DownloadUserModalInfo isDownload={isDownload} setIsDownload={setIsDownload} />

index.js

export const shareImageCreate = async (e, captureDivRef1, showMessage, showTabs, setSharePlease, clickedTabs, setDownloadCard) => {
    try {
        setSharePlease({
            text: "Please wait..",
            disabled: true
        });

        if (setDownloadCard) {
            setDownloadCard({
                download: false,
                share: true
            })
        }
        const elementToCapture = captureDivRef1.current;
        const canvas = await html2canvas(elementToCapture, { scale: 3, useCORS: true });
        const imgDataUrl = canvas.toDataURL('image/png');
        const blob = await fetch(imgDataUrl).then((res) => res.blob());
        const formData = new FormData();
        formData.append('title', showMessage.heading);
        formData.append('message', showMessage.message);
        formData.append('type', showTabs.type);
        formData.append('category', showTabs.category);
        formData.append('occasion', showTabs.occasion);
        formData.append('tabs', clickedTabs.tabs);
        formData.append('image', blob, 'image.png');
        const url = process.env.REACT_APP_SHARE_IMAGE_URL;
        const response = await axios.post(url, formData);
        setSharePlease({
            text: "Share",
            disabled: false
        });
        if (setDownloadCard) {
            setDownloadCard({
                download: false,
                share: false
            })
        }
        // Navigate(`/share?image=${response.data.data._id}`);
        const newTab = window.open(`/share?image=${response.data.data._id}`, '_blank');
        if (newTab) {
            newTab.focus(); // Focus on the new tab if it was successfully opened
        }
        return;
    } catch (err) {
        console.log(err);
    }
}

export const handleDownloadClick = (e, downloadText, setDownloadText, captureDivRef1, title, sendData, alert, is_dom, scales, downloadedImage, setDownloadCard, downloadSize, setShowInstagramPost, setIsDownload, setDownloadImageData) => {
    if (downloadText.disabled) {
        return;
    }
    let scale = 1;
    if (window.screen.width > 900) {
        scale = scales || 2;
    } else if ((window.screen.width > 500)) {
        scale = 2;
    } else {
        scale = 2
    }
    setDownloadText({
        text: "Please wait..",
        disabled: true
    });
    // setIsDownload(false);
    // const originalWidthStyle1 = captureDivRef1.current.offsetWidth;
    // const originalHeightStyle1 = captureDivRef1.current.offsetHeight;

    // console.log(originalWidthStyle1, originalHeightStyle1, "kjkjkjk")
    // const el = document.getElementById("sizeChange");
    if (downloadSize === "1") {
        setShowInstagramPost(true)
        // el.classList.add("insta-post")
    }


    if (setDownloadCard) {
        setDownloadCard({
            download: true,
            share: false
        })
    }

    // console.log("download check", downloadSize)
    setTimeout(() => {
        let elementToCapture = "";
        let recall = false;
        elementToCapture = captureDivRef1.current;

        // const originalWidthStyle = elementToCapture.offsetWidth;
        // const originalHeightStyle = elementToCapture.offsetHeight;

        elementToCapture.classList.add('instagram-size-1080');



        let originalImage;
        if (captureDivRef1.current.querySelector("div#image-div")) {
            // console.log("test22222",downloadedImage)
            originalImage = captureDivRef1.current.querySelector("div#image-div")?.style.backgroundImage;
        }
        if (captureDivRef1.current.querySelector("img#image-div")) {
            // console.log("test33333333",downloadedImage)

            originalImage = captureDivRef1.current.querySelector("img#image-div")?.src;
        }

        if (downloadedImage) {

            if (captureDivRef1.current.querySelector("div#image-div")) {
                const divImage = elementToCapture.querySelector("div#image-div");
                divImage.style.backgroundImage = `url("${downloadedImage}")`;

                // // Execute a function after the image has finished loading
                // divImage.onload = function() {
                //     // Run your function here
                if (!recall) {
                    abcd();
                }
                // };
            }
            if (captureDivRef1.current.querySelector("img#image-div")) {
                const imgElement = elementToCapture.querySelector("img#image-div");
                imgElement.src = downloadedImage;
                // Execute a function after the image has finished loading
                imgElement.onload = function () {
                    // Run your function here
                    if (!recall) {
                        abcd();
                    }
                };

            }
        } else {
            abcd()
        }

        function abcd() {
            let width, height, owidth, oheight;
            owidth = elementToCapture.offsetWidth;
            oheight = elementToCapture.offsetHeight;
            // const originalWidthStyle = mainImageElement.style.width;
            // const originalHeightStyle = mainImageElement.style.minheight;
            // console.log(originalWidthStyle,originalHeightStyle,"originalHeightStyle")
            // mainImageElement.style.width = `${desiredWidth}px`;
            // mainImageElement.style.minheight = `${desiredMinHeight}px`;

            const paragraphElement = captureDivRef1.current.querySelector('#template-message');
            let originalSize = "";

            // <option value="0">same size</option>
            // <option value="1">1080x1080</option>
            // <option value="2">1080x566</option>
            // <option value="3">1080x1350</option>


            if (downloadSize === '0') {
                width = elementToCapture.offsetWidth; // Use the current width of the element
                height = elementToCapture.offsetHeight; // Use the current height of the element
            }
            else if (downloadSize === '11') {
                width = 1080;
                height = 1080;
                if (paragraphElement) {
                    let originalSize = paragraphElement.style.fontSize;
                    if (originalSize === "") {
                        originalSize = "20px";
                    }
                    const size2 = (parseInt(originalSize) * 2)
                    paragraphElement.style.fontSize = `${size2}px`
                    // console.log(size2,"paragraphElement",paragraphElement,originalSize)

                }
            }
            else if (downloadSize === '2') {
                width = 1080;
                height = 566;
                if (paragraphElement) {
                    const originalSize = paragraphElement.style.fontSize;
                    const size2 = (parseInt(originalSize) * 2)
                    paragraphElement.style.fontSize = `${size2}px`;
                    // console.log(size2,"paragraphElement")

                }
            }
            else if (downloadSize === '3') {
                width = 1080;
                height = 1350;
                if (paragraphElement) {
                    const originalSize = paragraphElement.style.fontSize;
                    const size2 = (parseInt(originalSize) * 2)
                    paragraphElement.style.fontSize = `${size2}px`
                    // console.log(size2,"paragraphElement")

                }
            }

            // elementToCapture.style.width = `${width}px`;
            // elementToCapture.style.height = `${height}px`;
            // console.log("test11111111",downloadedImage,scale)
            // Calculate the scale factor to fit the element into the desired size
            // const scaleFactor = Math.min(width / elementToCapture.offsetWidth, height / elementToCapture.offsetHeight);
            html2canvas(elementToCapture, {
                // width: width,
                // height: height,
                scale: downloadSize === '0' ? scale : 1,
                quality: 1,
                useCORS: true,
                x: -0.2,
                y: 0,
                backgroundColor: "transparent",
                onclone: function (clonedDoc) {
                    const clonedElement = clonedDoc.getElementsByClassName('instagram-size-1080')[0];
                    const paragraphElement = clonedElement.querySelector('#template-message');
                    if (downloadSize === "1") {
                        clonedElement.classList.add('insta-post');

                        if (paragraphElement) {
                            let originalSize = paragraphElement.style.fontSize;
                            if (originalSize === "") {
                                originalSize = "20px";
                            }
                            const size2 = (parseInt(originalSize) * 2)
                            paragraphElement.style.fontSize = `${size2}px`
                        }
                        clonedElement.style.width = `1080px`;
                        clonedElement.style.height = `1080px`;
                    }

                    // console.log(elementToCapture,"clokkkkk")
                }
            }).then((canvas) => {

                const random4DigitNumber = Math.floor(1000 + Math.random() * 9000);
                let filename = "";
                if (title === "Others")
                    filename = `varnz_message_${random4DigitNumber}.png`;
                else
                    filename = `varnz_${title.toLowerCase().replace("Happy ", "")}_message_${random4DigitNumber}.png`;
                const dataURL = canvas.toDataURL('image/png');

                
                const a = document.createElement('a');
                a.href = dataURL;
                a.download = `${filename}`;
                console.log(dataURL, 'dataURL');
                
                a.click();
                alert.success("Downloaded Successfully!", {
                    timeout: 3000
                });

                // elementToCapture.style.width = `${originalWidthStyle}px`;
                // elementToCapture.style.height = `${originalHeightStyle1}px`;
                // if(paragraphElement){
                // paragraphElement.style.fontSize = originalSize;

                // }
                elementToCapture.classList.remove('instagram-size-1080');
                setDownloadText({
                    text: "Download",
                    disabled: false
                });
                if (setIsDownload) {
                    setIsDownload(true);
                }
                setShowInstagramPost(false)
                if (setDownloadCard) {
                    setDownloadCard({
                        download: false,
                        share: false
                    })
                }

                // sendData("download-successfully")
                if (downloadedImage) {
                    if (captureDivRef1.current.querySelector("div#image-div")) {
                        captureDivRef1.current.querySelector("div#image-div").style.backgroundImage = originalImage;
                    }
                    if (captureDivRef1.current.querySelector("img#image-div")) {
                        captureDivRef1.current.querySelector("img#image-div").src = originalImage;
                    }
                }
                recall = true;
            });
        }
    }, 100)

};
export const Result_Overlay = ({ index, downloadText, setDownloadText, captureDivRef1, title, sendData, showMessage, showTabs, handleClick, data, alert, design, clickedTabs, setDownloadCard, isDisabled, setShowInstagramPost, bannerThemeResponse, setIsDownload }) => {
    const [sharePlease, setSharePlease] = useState({
        text: "Share",
        disabled: false
    });
    const [printPage, setPrintPage] = useState({
        text: "Print",
        disabled: false
    });
    const [size, setSize] = useState("0");
    const [showSize, setShowSize] = useState(false);
    const [isHovered, setIsHovered] = useState({});
    const handleMouseLeave = (index) => {
        setIsHovered({
            [index]: false
        })
    }
    const handleMouseEnter = (index) => {
        setIsHovered({
            [index]: true
        })
    }

    // console.log(isDisabled,"isDisabled")
    return (
        <>
            <div className="result_overlay_info new-action-btns" id={`social-btn_${index}`}>
                <div className="action-btns-left">
                    <div className="inner_performing_buttons greeting-card-share card-share" onClick={(e) => shareImageCreate(e, captureDivRef1, showMessage, showTabs, setSharePlease, clickedTabs, setDownloadCard)}>
                        <a href="javascript:void(0);"
                            style={{
                                cursor: sharePlease.disabled ? 'not-allowed' : 'pointer',
                                background: isHovered[`share-${index}`] ? bannerThemeResponse?.button_hover_color : bannerThemeResponse?.button_main_color,
                                border: isHovered[`share-${index}`] ? `2px solid ${bannerThemeResponse?.button_hover_color}` : `2px solid ${bannerThemeResponse?.button_main_color}`
                            }}
                            className="greeting-card-share"
                            onMouseEnter={(e) => { handleMouseEnter(`share-${index}`) }}
                            onMouseLeave={(e) => { handleMouseLeave(`share-${index}`) }}
                        >

                            {
                                sharePlease.disabled ? (
                                    <i id="loader" class="fas fa-spinner loader"></i>

                                ) : (
                                    <h1>img</h1>
                                )
                            }
                            <span className="action-btn-tooltip">Share</span>
                        </a>
                    </div>
                    <div className="inner_performing_buttons edit message-edit edit-card" >
                        <Link
                            to={`/inline-editor`} onClick={() => { handleClick(data, design, showTabs); localStorage.setItem("hompepage", "edit_page"); }}
                            className="message-edit"
                            target="_blank"
                            style={{
                                background: isHovered[`edit-${index}`] ? bannerThemeResponse?.button_hover_color : bannerThemeResponse?.button_main_color,
                                border: isHovered[`edit-${index}`] ? `2px solid ${bannerThemeResponse?.button_hover_color}` : `2px solid ${bannerThemeResponse?.button_main_color}`
                            }}
                            onMouseEnter={(e) => { handleMouseEnter(`edit-${index}`) }}
                            onMouseLeave={(e) => { handleMouseLeave(`edit-${index}`) }}
                        >
                            <img src={edit} alt="Image" className="message-edit" />
                            <span className="action-btn-tooltip">Edit</span>
                        </Link>
                    </div>
                    <div className="inner_performing_buttons edit message-edit edit-card " style={{ fontSize: "23px" }} >
                        <Link
                            to={`javascript:void();`} onClick={(e) => { handlePrint({ e, captureDivRef1, setPrintPage }) }}
                            className="message-edit"
                            style={{
                                background: isHovered[`print-${index}`] ? bannerThemeResponse?.button_hover_color : bannerThemeResponse?.button_main_color,
                                border: isHovered[`print-${index}`] ? `2px solid ${bannerThemeResponse?.button_hover_color}` : `2px solid ${bannerThemeResponse?.button_main_color}`
                            }}
                            onMouseEnter={(e) => { handleMouseEnter(`print-${index}`) }}
                            onMouseLeave={(e) => { handleMouseLeave(`print-${index}`) }}
                        >
                            {
                                printPage.disabled ? (
                                    <i id="loader" class="fas fa-spinner loader"></i>

                                ) : (
                                    <i class="fas fa-print"></i>
                                )
                            }

                            <span className="action-btn-tooltip">Print</span>
                        </Link>
                    </div>
                </div>
                <div className="action-btns-right">
                    <div className="dowbload-dropdown">
                        <div id="download-btn" className="greeting-card-download download-btn" onClick={(e) => {
                            if (isDisabled) {
                                return;
                            }
                            handleDownloadClick(e, downloadText, setDownloadText, captureDivRef1, title, sendData, alert, "", "", data.image?.downloadedImage, setDownloadCard, size, setShowInstagramPost, setIsDownload)
                        }
                        }
                            style={{
                                cursor: downloadText.disabled ? 'not-allowed' : isDisabled ? 'not-allowed' : 'pointer',
                                background: isHovered[`dl-${index}`] ? bannerThemeResponse?.button_hover_color : bannerThemeResponse?.button_main_color,
                                border: isHovered[`dl-${index}`] ? `2px solid ${bannerThemeResponse?.button_hover_color}` : `2px solid ${bannerThemeResponse?.button_main_color}`
                            }}
                            onMouseEnter={(e) => { handleMouseEnter(`dl-${index}`) }}
                            onMouseLeave={(e) => { handleMouseLeave(`dl-${index}`) }}
                        >
                            <a style={{ cursor: downloadText.disabled ? 'not-allowed' : isDisabled ? 'not-allowed' : 'pointer' }} href="javascript:void(0);" className="">
                                {
                                    downloadText.disabled ? (
                                        <i id="loader" class="fas fa-spinner loader"></i>
                                    ) : (
                                        <img src={download} alt="Image" className="greeting-card-download" />
                                    )
                                }
                            </a>
                            Download
                        </div>
                        <div className="download-arrow " onClick={() => setShowSize(!showSize)}
                            style={{
                                background: isHovered[`dl-${index}`] ? bannerThemeResponse?.button_hover_color : bannerThemeResponse?.button_main_color,
                            }}
                            onMouseEnter={(e) => { handleMouseEnter(`dl-${index}`) }}
                            onMouseLeave={(e) => { handleMouseLeave(`dl-${index}`) }}
                        ><i class="fa-solid fa-caret-down"></i></div>
                        <div className={`download-dropdown-option ${showSize && 'active'}`}>
                            <ul>

                                <li
                                    id="insta-post"
                                    onClick={(e) => {
                                        if (isDisabled) {
                                            return;
                                        }
                                        setShowSize(false);
                                        handleDownloadClick(e, downloadText, setDownloadText, captureDivRef1, title, sendData, alert, "", "", data.image?.downloadedImage, setDownloadCard, "1", setShowInstagramPost, setIsDownload)
                                    }
                                    }>
                                    Instagram (1:1)
                                </li>
                            </ul>
                        </div>

                    </div>

                </div>

            </div>
            {
                // downloadText.disabled
                downloadText.disabled &&
                <div style={{ width: "100%", height: "100%" }} className="please-wait new-please-wait">
                    <div class="skype-loader">
                        <div class="dot">
                            <div class="first"></div>
                        </div>
                        <div class="dot"></div>
                        <div class="dot"></div>
                        <div class="dot"></div>
                    </div>
                </div>
            }

        </>
    )
}

// stay with us popup
export const DownloadUserModalInfo = ({ isDownload, setIsDownload, downloadImageData }) => {

    const [showNoThanks, setShowNoThanks] = useState(false);
    const [showPopup, setShowPopup] = useState(isDownload);
    const [formData, setFormData] = useState({
        name: "",
        email: ""
    });
    const [submitBtn, setSubmitBtn] = useState({
        text: "Submit",
        disabled: false
    });
    const [formError, setFormError] = useState({});
    const alert = useAlert();

    const handleFormData = (e) => {
        const key = e.target.name;
        const value = e.target.value;

        setFormData((oldData) => {
            return {
                ...oldData,
                [key]: value
            }
        });
    }

    const handleSubmit = async (e) => {
        e.preventDefault();

        let isError = false;
        if (formData.name === "") {
            isError = true;
            setFormError((oldData) => {
                return {
                    ...oldData,
                    name: "name is required!"
                }
            });
        }
        if (formData.email === "") {
            isError = true;
            setFormError((oldData) => {
                return {
                    ...oldData,
                    email: "email is required!"
                }
            });
        }

        if (isError) {
            setTimeout(() => {
                setFormError({});
            }, 3000);
            return;
        }

        try {
            setSubmitBtn({
                text: "Please wait ...",
                disabled: true
            });
            const formDataValue = localStorage.getItem("formData");
            const data = {
                name: formData.name,
                email: formData.email,
                formData: JSON.parse(formDataValue)
            }
            const response = await axios.post(process.env.REACT_APP_VISITED_USERS, data);
            if (response.data.status === 1) {
                alert.success("Form submitted successfully! Thanks", {
                    timeout: 10000,
                    position: "top right"
                });
                setShowPopup(false);
                setIsDownload(false);
                setFormData({
                    name: "",
                    email: ""
                })
                // setResponseStatus(true);
            } else {
                if (response.data.status === 2) {
                    alert.success(response.data.message, {
                        timeout: 10000,
                        position: "top right"
                    });
                    setShowPopup(false);
                    setIsDownload(false);
                    setFormData({
                        name: "",
                        email: ""
                    })
                } else {
                    setFormError({
                        email: response.data.message
                    });
                }

            }
        } catch (error) {
            setFormError({
                email: error.response.data.message
            });
        } finally {
            setSubmitBtn({
                text: "Submit",
                disabled: false
            });
            setTimeout(() => {
                setFormError({})
            }, 3000);

        }
    }

    useEffect(() => {
        setShowPopup(isDownload);
        setShowNoThanks(false);

        if (isDownload) {
            const timer = setTimeout(() => {
                setShowNoThanks(true);
            }, 1000);

            return () => clearTimeout(timer);
        }
    }, [isDownload]);


    const useCardModelDesign = (
        <>
            <Modal
                className="how-work-popup user-info-download"
                show={showPopup}
                onHide={() => {
                    setShowPopup(false);
                    setIsDownload(false);
                }}
            >
                <Modal.Header closeButton>
                    <div className="user-info-pop-header">
                        <img src={headerImage} />
                    </div>
                </Modal.Header>
                <Modal.Body>
                    <h4>Stay with us!</h4>
                    <p>Congratulations on downloading the beautiful AI greetings card. Let us know about you a little to keep you posted with latest updates on varnz.</p>
                    <div className="col-12" >
                        <form className="user-info-form" onSubmit={handleSubmit} autoComplete="off">
                            <div class="form-group">
                                {/* <label for="exampleInputEmail1">Name: <span style={{color:"red"}}>*</span></label> */}
                                <input
                                    class="form-control"
                                    type="text"
                                    id="fname"
                                    name="name"
                                    placeholder="Name"
                                    value={formData.name}
                                    onChange={handleFormData}
                                />
                                {
                                    formError.name && <span style={{ color: "red" }}>{formError.name}</span>
                                }
                            </div>
                            <div class="form-group">
                                {/* <label for="exampleInputEmail1">Email: <span style={{color:"red"}}>*</span></label> */}
                                <input
                                    class="form-control"
                                    type="email"
                                    id="email"
                                    name="email"
                                    placeholder="Email"
                                    value={formData.email}
                                    onChange={handleFormData}
                                />
                                {
                                    formError.email && <span style={{ color: "red" }}>{formError.email}</span>
                                }
                            </div>
                            <div class="submit-form">
                                <button type="submit" class="blue-btn cstm-btn swu-forum-submit" disabled={submitBtn.disabled}>{submitBtn.text}</button>
                            </div>
                            {showNoThanks && (
                                <a href="javascript:void();" className="swu-forum-skip" onClick={() => {
                                    setShowPopup(false);
                                    setIsDownload(false);
                                }}>No thanks, I'll do it Later</a>
                            )}
                        </form>
                    </div>
                </Modal.Body>
            </Modal>
        </>
    )
    return useCardModelDesign;
}

I need to ensure that handleDownloadClick is executed only after the form is submitted successfully. However, I’m unsure how to properly integrate this function into the form submission process.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật