Home > Software engineering >  preventDefault() method not preventing page reload ReactJS
preventDefault() method not preventing page reload ReactJS

Time:07-04

I am trying to upload files using multer or formidable. The files are uploaded properly and also stored in the public folder. I used create-react-app to start with React project.

The problem arises when I click on the submit button to upload the data. I used the fetch API for making the POST request. The page reloads after I click on the submit button, and anything I log on the console is refreshed as well. This was also answered here, but I want to know how do I prevent my page from reloading? Should I store my images outside the public folder?

Here is my handleSubmit() function that calls when form is submitted:-

const handleSubmit = async (e) => {
    e.preventDefault();
    let formData = new FormData();
    formData.append("poster", document.getElementById('file').files[0]);
    let res = await fetch("http://localhost:5000/api/post/exhibition", {
       method: "POST",
       body: formData
    })
    const json = await res.json()
    console.log(json)
 }

EDIT:- Handling onSubmit

<form onSubmit={handleSubmit} encType="multipart/form-data">
....
</form>

CodePudding user response:

This is because when your upload is successful, webpack detects a new file and reloads the page.

from https://github.com/facebook/create-react-app/issues/2541#issuecomment-308750412

I don't think we'll do this as it seems like people generally don't use public folder for uploads. And it wouldn't work in production anyway.
I would recommend to use a separate server (which you need anyway) and separate folder for image uploads, and have the app load images from a different host/port (just like it would in production, e.g. from a CDN).

CodePudding user response:

if you are using that function in onsubmit attribute of the form you need to return false from that function

  const handleSubmit = async (e) => {
    e.preventDefault();
    let formData = new FormData();
    formData.append("poster", document.getElementById('file').files[0]);
    let res = await fetch("http://localhost:5000/api/post/exhibition", {
       method: "POST",
       body: formData
    })
    const json = await res.json()
    console.log(json)
    return false
 }
  • Related