After clicking the submit button, the form will be reset before submitting.
I created a form using Formik. I'm trying to use Formik's resetForm to reset the form after submission. But it resets the form before submitting and submits an empty form. This is my form:
<Formik onSubmit={handleFormSubmit} initialValues={{ content: "", picture: "", }} > {({ values, handleBlur, handleChange, handleSubmit, setFieldValue, resetForm, }) => ( <form onSubmit={handleSubmit}> <Field as="textarea" onBlur={handleBlur} onChange={handleChange} value={values.content} name="content" /> <Dropzone acceptedFiles=".jpg, .jpeg, .png" multiple={false} onDrop={(acceptedFiles) => setFieldValue("picture", acceptedFiles[0]) } > {({ getRootProps, getInputProps }) => ( <div {...getRootProps()}> <input {...getInputProps} /> {!values.picture ? ( <p>在这里添加图片</p> ) : ( values.picture.name )} </div> )} </Dropzone> <button type="submit" onClick={resetForm}>提交</button> </form> )} </Formik>
I'm not sure if I should share the handleFormSubmit function, but here is it:
const handleFormSubmit = async (values, onSubmitProps) => { const formData = new FormData(); for (let value in values) { formData.append(value, values[value]); } formData.append("picturePath", values.picture.name); fetch(`http://localhost:5000/api/home-profile/${data[0]._id}`, { method: "PUT", body: formData, headers: { Authorization: "Bearer " + token, }, }) .then((res) => { console.log(res.status); }) .catch((err) => { console.log(err); }); };
Delete onClick={resetForm}:
Then in your handleFormSubmit:
...
If it is useful to you, please tell me.