When clicked on submit button, form gets reseted before submited.
I have a form created with Formik. I'm trying to reset the form after submit with resetForm from Formik. But it resets the form before submitting it and submits an empty form. Here's 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>Add Picture Herse</p>
) : (
values.picture.name
)}
</div>
)}
</Dropzone>
<button type="submit" onClick={resetForm}> gönder</button>
</form>
)}
</Formik>
I'm not sure if I should share the handleFormSubmit function but here it is:
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);
});
};
Remove onClick={resetForm} :
<button type="submit"> gönder</button>
Then in your handleFormSubmit:
...
.then((res) => {
console.log(res.status);
})
.catch((err) => {
console.log(err);
})
.finally(() => {
resetForm(); //this
});
Let me know if it works for you