I'm trying to reset the inputs in my formik Form on submit. It seems I'm supposed to use resetForm() to do that but i get the error:
src\components\CommentSubmition\inCommentSubmition.js Line 19:13: 'resetForm' is not defined no-undef
Here's my component:
import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import {createComment} from '../../services/CommentLocalStorage.js'
import * as Yup from 'yup';
function CommentForm(props){
return (
<Formik
initialValues={{ autor: '', content: ''}}
validationSchema={Yup.object({
autor: Yup.string().required('Required'),
content: Yup.string().required('Required')
})}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
createComment(props.pageEnum, props.articleId, values.autor, values.content)
setSubmitting(false);
},400);
resetForm();
}}
>
<Form>
<label htmlFor="autor">Nome</label>
<Field name="autor" type="autor" placeholder="Nome"/>
<ErrorMessage name="autor" />
<br/>
<label htmlFor="content">Comentário</label>
<Field name="content" type="content" placeholder="Comentário" />
<ErrorMessage name="content" />
<br/>
<button type="submit">Submit</button>
</Form>
</Formik>
);
};
export default CommentForm;
It seems most people make something like this:
const formik = some configuration
And then they use it like
formik.resetForm()
And instead I'm using the Formik component with all the stuff inside it (I did it based on an example available on the official tutorials). If possible i'd like to keep it like that and still make the form reset.
Pass resetForm as a parameter to your onSubmit function. That should give your function access to the resetForm method from Formik thereby getting rid of the error and successfully reset the form. If you want to use any methods from the formik library inside your onSubmit function, first pass a parameter to the function so you can have access to the formik method. Let me know if this helps
import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import {createComment} from '../../services/CommentLocalStorage.js'
import * as Yup from 'yup';
function CommentForm(props){
return (
<Formik
initialValues={{ autor: '', content: ''}}
validationSchema={Yup.object({
autor: Yup.string().required('Required'),
content: Yup.string().required('Required')
})}
onSubmit={(values, { setSubmitting, {resetForm }) => { //<--- See here for code added
setTimeout(() => {
createComment(props.pageEnum, props.articleId, values.autor, values.content)
setSubmitting(false);
},400);
resetForm();
}}
>
<Form>
<label htmlFor="autor">Nome</label>
<Field name="autor" type="autor" placeholder="Nome"/>
<ErrorMessage name="autor" />
<br/>
<label htmlFor="content">Comentário</label>
<Field name="content" type="content" placeholder="Comentário" />
<ErrorMessage name="content" />
<br/>
<button type="submit">Submit</button>
</Form>
</Formik>
);
};
export default CommentForm;