I’ve been trying to submit a file (image) and a quiz in a form. They both have separate buttons but the file button must be pressed first for the image path to be added to the question post data state.
However, for some reason, the page refreshes after the 2nd or 3rd image upload. This only occurs when uploading the file.
// image upload form <form onSubmit={handleImageUpload} encType="multipart/form-data"> <input type="file" name="photo" onChange={handleFileChange} /> <button type="submit" className="btn"> submit </button> </form>
const handleImageUpload = (e) => { e.preventDefault(); const formData = new FormData(); formData.append('photo', file); axios.post(uploadAPI, formData).then(res => setPost({...post, image: res.data.file})); }
Advertisement
Answer
swapping the onClick
to the handle function and having the onSubmit
call e.preventDefault()
fixed my issue of having multiple forms on a page and random refreshes after submitting different forms in succession.
<form onSubmit={(e) => {e.preventDefault()}} encType="multipart/form-data"> <input type="file" name="photo" onChange={handleFileChange} /> <button type="submit" className="btn" onClick={handleImageUpload}> submit </button> </form>