r121
r121

Reputation: 2728

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.

Upvotes: 0

Views: 59

Answers (2)

Ktoxcon
Ktoxcon

Reputation: 434

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()

Upvotes: 1

ilkerkaran
ilkerkaran

Reputation: 4344

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>

Upvotes: 0

Related Questions