'Why Browser gets round trip/refreshed after uploading image more than 9 MB in reactjs?

I have a ReactJS APP. The logic in the APP needs to make an http post request to nodejs uploading image api, capturing the response from api give some errors and sometimes uploads, and then refreshed the browser instantly. My problem is capturing the http response from nodejs api asynchronously and returning it to the image/display list without a browser refresh.

When I try to upload more than 6MB to 46MB then a browser refresh must be occured.

--- ImageComponent.js

function EditImageSlider({ breadcrumb, pageName, setLoader, showToast }) {


const history = useHistory();   
const list = useSelector((state) => state.imagecrop.list);
const detail = useSelector((state) => state.imagecrop.detail);
const row = useSelector((state) => state.imagecrop.row);
const imageCropWidth = useSelector((state) => state.imagecrop.imageCropWidth);
const imageCropHeight = useSelector((state) => state.imagecrop.imageCropHeight);
const croppedImage = useSelector((state) => state.imagecrop.croppedImage);
const Image = useSelector((state) => state.imagecrop.Image);
const ImageName = useSelector((state) => state.imagecrop.ImageName);
const errorMessage = useSelector((state) => state.imagecrop.errorMessage);
const umodalShow = useSelector((state) => state.imagecrop.umodalShow);
const cropSize = useSelector((state) => state.imagecrop.cropSize);
const IsDisabled = useSelector((state) => state.imagecrop.IsDisabled);
const [currentImage, setCurrentImage] = useState("");  
const [croppedAreaPixels, setCroppedAreaPixels] = useState(null); 
    const singlefileSelectedHandler = async (e) => {
        //debugger;
        e.preventDefault();
        //setIsDisabled(true);
        dispatch(imageCropActions.setIsDisabled({ IsDisabled: true }));
        content = "";

        if (!e.target.files || e.target.files.length <= 0) {
            return -1;
        }

        if (detail && detail.Content) {
            content = detail.Content;
        }
        //let imageList = "";
        const selectedImage = e.target.files[0];
        let imageSizeInMBs = selectedImage.size ? selectedImage.size / 1024 / 1024 : 0;
        if (selectedImage && imageSizeInMBs > 50) {
            dispatch(imageCropActions.setIsDisabled({ IsDisabled: false }));
            showToast("Information!", "Image size can't be greater than 8MB.");
           return -1;
        }
        const filename =
            selectedImage && selectedImage.name
                ? new Date().valueOf() +
                  "_" +
                  selectedImage.name.replace(/\\/g, "").replace(/ /g, "").replace(/'/g, "").replace(/"/g, "").replace(/`/g, "")
                : "";
        imageCropHeight ? parseInt(imageCropHeight) : 0 });      
      
        setCurrentImage(selectedImage);
        const localconvertedImage = URL.createObjectURL(selectedImage);        
        dispatch(
            imageCropActions.setImageAttributes({
                Image: localconvertedImage,
                ImageName: filename,
                croppedImage: localconvertedImage,
                show: true,
                width: imageCropWidth ? parseInt(imageCropWidth) : 0,
                height: imageCropHeight ? parseInt(imageCropHeight) : 0,
                IsDisabled: false,
            })
        );       
    };

const onSaveImage = async (event) => {
        //debugger;
        event.preventDefault();
        if (validate() < 0) {
            return -1;
        }
        try {
            let filename = ImageName ? ImageName : "";
            if (currentImage) {               
                //debugger;
                dispatch(sendImageData(filename, croppedAreaPixels, currentImage));
            }
        } catch (err) {
            debugger;
            dispatch(imageCropActions.setImage(""));
            dispatch(imageCropActions.setImageName(""));                     
            console.log(err);
        }
    }; 

    return (
            <>
                <label className="form-label" htmlFor="customFile">
                    Upload image
                </label>
                <div className="custom-file">
                    <input type="file" className="custom-file-input" id="customFile" onChange={singlefileSelectedHandler} />
                    <label className="custom-file-label" htmlFor="customFile">
                        Choose file
                    </label>
                </div>
<div className="form-row justify-content-end">
                <Button className="btn btn-secondary" disabled={IsDisabled} onClick={onSaveImage }>
                    Save
                </Button>
            </div>
            </>
        );
    }


--- ImageActions.js 
export const sendImageData = (filename, croppedAreaPixels, cropImage) => {
    return async (dispatch) => {
const sendRequest = async () => {
            //debugger;           
            let uploadedImageUrl = "";
            let uploadedImageName = "";
            let uploadedServerPath = "";
            let uploadurl = "";
            const formData = new FormData();
            formData.append("coord", JSON.stringify(croppedAreaPixels));
            formData.append("image", cropImage);
            let submitUrl = process.env.REACT_APP_SERVER_DOMAIN + `/uploaddetail`;
            //debugger;
            const responseWebApi = await axios.post(submitUrl, formData, {
                timeout: 30000,
                timeoutErrorMessage: "The request timeout has been occured during the Image Upload",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "multipart/form-data",
                },
            });

            const jsonRes = responseWebApi ? responseWebApi.data : "";
            if (jsonRes) {             
                return {
                    ImageName: jsonRes.imagename,
                    ImageServerPath: jsonRes.serverpath,
                    ImageFullUrl: jsonRes.fullurl,
                    ImageUrl: jsonRes.url,
                };
            }
        };
        try {
            const returnData = await sendRequest();
            dispatch(imageCropActions.updateCropImage({ newRow: returnData, show: false, IsDisabled: false }));
            debugger;
            return 0;
        } catch (error) {
            debugger;         
        }
};
};

The error I get here is Uncaught TypeError:

Browser Headers: 
Request URL: http://localhost:8001/uploaddetail
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:8001
Referrer Policy: strict-origin-when-cross-origin

Browser Response tab: Failed to load response data : No resource is given identifier found.

After that a browser refresh occurs. Any help is appreciated.

. I understand why I'm getting the error (because apiRes is out of scope), I just can't figure out how to do it right. Any help much appreciated!

  -- PAckage.json
    {
        "name": "admin-panel",
        "version": "0.1.0",
        "private": true,
        "dependencies": {    
            "@reduxjs/toolkit": "^1.7.2",
            "@testing-library/jest-dom": "^5.12.0",
            "@testing-library/react": "^11.2.7",
            "@testing-library/user-event": "^12.8.3",
            "axios": "^0.26.0",
            "bootstrap": "^4.6.0",
            "faker": "^5.5.3",
            "node-sass": "^4.14.1",
            "rangeslider-pure": "^0.4.11",
            "react": "^17.0.2",
            "react-bootstrap": "^1.6.1",
            "react-bootstrap-sweetalert": "^5.2.0",
            "react-data-table-component": "^6.11.7",
            "react-dom": "^17.0.2",
            "react-easy-crop": "^4.0.0",
            "react-hook-form": "^7.12.2",
            "react-icons": "^4.2.0",
            "react-nestable": "^2.0.0",
            "react-redux": "^7.2.6",
            "react-router-dom": "^5.2.0",
            "react-scripts": "^4.0.3",
            "styled-components": "^5.3.0",
            "web-vitals": "^1.1.2",
            "yup": "^0.32.9"
        },
        "scripts": {
            "start": "set PORT=3001 &&react-scripts start",
            "build": "react-scripts build",
            "test": "react-scripts test",
            "eject": "react-scripts eject"
        },
        "eslintConfig": {
            "extends": [
                "react-app",
                "react-app/jest"
            ]
        },
        "browserslist": {
            "production": [
                ">0.2%",
                "not dead",
                "not op_mini all"
            ],
            "development": [
                "last 1 chrome version",
                "last 1 firefox version",
                "last 1 safari version"
            ]
        },
       
    }

I have tried to create a full sample code example at https://codesandbox.io/s/vigorous-heisenberg-vbdwo?file=/src/EditImageSlider.js

Is there any restriction in the react for uploading image file size ?

I found a link and image is not being uploaded there as well.

enter image description here

https://codepen.io/ccnokes/pen/wyBYOd

I have added more code in the sample code. If anyone can see it then please



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source