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": ""
}
CodePudding user response:
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>
)
})