Home > database >  Why is the preventDefault() method not working for me in my react application?
Why is the preventDefault() method not working for me in my react application?

Time:10-30

I used a form to capture input from user. But once the user clicks on the submit button, the page reloads. I don't want it to reload. That was why I decided to use preventDefault() method. How can I get this to work?

const handleHeaderValueUpdate = async ( headerId, e) =>{
e.preventDefault()
console.log(headerId)

  setUpdating(true)
  const updatedHeaderValue = {
  username: user.username,
  websiteName,
  sitesubName,
  };
  if(file){                    //logic behind uploading image and the image name
    const data = new FormData();
    const filename = Date.now()   file.name;
    data.append("name", filename);
    data.append("file", file);
    updatedHeaderValue.headerImg = filename;

  
    try{
    await axios.post("/upload", data)//handles the uploading of the image
    //setUpdated(true)
    }catch(err){
        dispatch({type: "UPDATE_FAILURE"})
    }
    }

    try{
    
    await axios.put("/headervalue/"   headerId, updatedHeaderValue)  
     setUpdating(false);
     setTextUpdate(true)
     //setUpdated(true)
  


 }catch(err){
   console.log(err)
}

}

Here is part of the form:

 <form onSubmit={()=>handleHeaderValueUpdate(headerId)} className="dashboard-form">

        <div className='dasboard-input-div'>
          <p className="dashboard-label">Website Name</p>
          {dashboardEditMode ? <input className="dashboard-input" type="text" placeholder={singleValues.websiteName} autoFocus
             onChange={(e) => setWebsiteName(e.target.value)}
             required
            /> : 
            <input className="dashboard-input" type="text" placeholder= {singleValues.websiteName} readOnly/>
          }
  </form>

Here is the submit button

{dashboardEditMode && <button className={updating ? "updateModeBTN-unclick updateModeBTN" : "updateModeBTN"} type="submit">Update</button>}

CodePudding user response:

The problem is you do not send the event to the handleHeaderValueUpdate function. You should change:

<form onSubmit={()=>handleHeaderValueUpdate(headerId)}

to:

<form onSubmit={(e) => handleHeaderValueUpdate(headerId, e)}

You can take a look at this sandbox for a live working example.

  • Related