'Formik form submitting empty object
I'm new to react and Formik and I'm trying to create a login form. For some reason, the request to the API is sent as the default initial object I created. Here is the code:
import { Formik, Form } from 'formik';
import { observe } from 'mobx';
import { observer } from 'mobx-react';
import React from 'react';
import { Input , Button } from 'semantic-ui-react';
import { useStore } from '../application/stores/store';
export default observer(function LoginForm() {
const {userStore} = useStore();
return (
<Formik
initialValues={{user:'', password:''}}
onSubmit={(values) => {
console.log(JSON.stringify(values, null, 2));
userStore.login(values)}
}
>
{({handleSubmit ,isSubmitting})=> (
<Form className='ui form' onSubmit={handleSubmit} autoComplete='off'>
<Input name='user' placeholder='User'/>
<Input name='password' placeholder='Password' type='password'/>
<Button loading={isSubmitting} positive content ='Login' type='submit' fluid/>
</Form>
)
}
</Formik>
)
})
and here is the result:
{
"user": "",
"password": ""
}
Solution 1:[1]
Use handleChange from formik
export default observer(function LoginForm() {
const {userStore} = useStore();
return (
<Formik
initialValues={{user:'', password:''}}
onSubmit={(values) => {
console.log(JSON.stringify(values, null, 2));
userStore.login(values)}
}
>
{({handleSubmit ,isSubmitting,handleChange})=> (
<Form className='ui form' onSubmit={handleSubmit} autoComplete='off'>
<Input name='user' placeholder='User' onChange={handleChange}/>
<Input name='password' placeholder='Password' type='password' onChange={handleChange}/>
<Button loading={isSubmitting} positive content ='Login' type='submit' fluid/>
</Form>
)
}
</Formik>
)
})
Solution 2:[2]
I added enableReinitialize={true}
and it worked for me.
Example:
<Formik
initialValues={registrationValues}
validationSchema={RegisterValidationSchema}
onSubmit={submitHandlerRegister}
enableReinitialize={true}
>
.....
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sukesh |
Solution 2 | Andreea Purta |