0

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.

2
  • Your problem is that your form does not have the action attribute, i.e. action="/link_to_some_page". This makes the form return to its default behavior, which is sending the data to its current URL, which is why you are experiencing this behavior. You either need to specify where the form data should be sent, or prevent the default behavior by applying the e.preventDefault()propagation to the form's submit. Alternatively, you can utilize AJAX and send the data asynchronously. Commented Apr 5, 2021 at 14:13
  • I already applied e.preventDefault() to the submit event and I post data to my API URL using axios Commented Apr 5, 2021 at 15:21

2 Answers 2

1

The problem with this code is in the async event handler, preventDefault needs to be called synchronously to have any effect at all.

You should call e.persist() before e.preventDefault()

Sign up to request clarification or add additional context in comments.

2 Comments

I did as you said, still it get reload on submit e.persist(); e.preventDefault(); const formData = new FormData(); formData.append('file', file);
@RishiPurwar Can you please upload it to condesandbox or something similar, that way it could be easier to debug.
0

Instead of using submit button and form onSubmit You can just use a normal button and bind the submit handler to onClick

<form>
                <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="button" onClick={onSubmit} value="Upload" className="btn btn-primary w-100" /> */}
                <button className="btn btn-primary w-100" type="submit">Upload</button>
            </form>

3 Comments

Now, I did this but still get reloaded <button className="btn btn-primary w-100" onClick={onSubmit}>Upload</button>
you removed onSubmit from form element right?
Yes, I removed onSubmit event feom the form

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.