Form get reloaded on submit reactjs

When I submit my form it gets reloaded, but when no file is selected, it doesn’t get reload, just show me an error message ‘No File Uploaded’.
It only gets reloaded when I submit the file.

I already used the e.preventDefault() to prevent reloading but it doesn’t work.

Component Code

import React, { Fragment, useState } from 'react'
import axios from 'axios'

const FileUpload = () => {
    const [file, setFile] = useState('');
    const [filename, setFilename] = useState('Choose File')
    const [uploadedFile, setUploadedFile] = useState({})

    const onChange = (e) => {
        setFile(e.target.files[0]);
        setFilename(e.target.files[0].name);
    }

    const onSubmit = async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('file', file);

        try {
            const res = await axios.post('/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })

            const { fileName, filePath } = res.data;

            setUploadedFile({ fileName, filePath });
            console.log(uploadedFile);
        } catch (err) {
            if (err.response.status === 500) {
                console.log("There was a problem with the server.");
            } else {
                console.log(err.response.data.msg);
            }
        }
    }

    return (
        <Fragment>
            <form onSubmit={onSubmit}>
                <div className="mb-3">
                    <label htmlFor="formFile" className="form-label">{filename}</label>
                    <input className="form-control" type="file" id="formFile" onChange={onChange} />
                </div>
                {/* <button type="submit" value="Upload" className="btn btn-primary w-100" /> */}
                <button className="btn btn-primary w-100" type="submit">Upload</button>
            </form>
        </Fragment>
    )
}

export default FileUpload

Anyone can please help me with this.

Hello there,

Would you mind being more specific? What gets reloaded?

Are you aware that React reloads components, when the associated state changes?


Also, this is not doing what you expect, because state hooks are asynchronous.

I mean page gets reloaded when I submit the form.

Yes, I know that, does it reload the whole page?

No, it does not.

The only thing I can think you can try is not making your onSubmit function asynchronous:

const onSubmit = (e) => {
  e.preventDefault();
  (async () => {
    // same as you have it
  })();
}

Hope this helps. Otherwise, someone else might have more insight.

1 Like

What do you get if you log out defaultPrevented and cancelable after preventDefault?

e.preventDefault();
console.log(e.defaultPrevented);
console.log(e.cancelable);

Not sure why async would cause any issues. If you have a live example we can look at that would help.

will try to do that
Thanks for your help

I don’t know why it’s causing issue.
I think If I’ll remove async then it’ll solve my problem

Thanks for your help

So did it fix the problem or not?

What do the properties I asked you to log out return? If true then you are already preventing the default. Not saying you do not have something causing a page refresh, just that it shouldn’t be the submit event.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.