1 year ago
#353268
Mohsen Amani
dispatching a reducer action resets form values react
I have forgot password page which obviously takes email input. After submitting the form I am displaying a toast notification confirming the success or error of operation.
I created a Notification components which is rendered when ever my application state has the object of notification filled.
By submitting the form I am then dispatching an action which fills the notification object. It works fine
But after dispatch the form loses its fields values
const {control, handleSubmit, setError, formState: {errors}, isSubmitting} = useForm({defaultValues: {email: ''}})
This is my form submit handler
const onSubmit = async data => {
if (Object.values(data).every(field => field.length > 0)) {
useJwt
.forgotPassword({email: data.email})
.then(res => dispatch(toastNotify({ status: "success", ...res.message })))
.catch(({response}) => {
if (response.status === 400 && response.data.hasOwnProperty('errors')) {
response.data.errors.forEach(error => setError(error['param'], {type: 'manual', message: error['msg']}))
} else {
// If I comment line below and log the response data, form values works fine
dispatch(toastNotify({type: "error", ...response.data}))
}
})
} else {
for (const key in data) {
if (data[key].length === 0) {
setError(key, {
type: 'manual'
})
}
}
}
}
This is my form
<Form className='auth-forgot-password-form mt-2' onSubmit={handleSubmit(onSubmit)}>
<div className='mb-2'>
<Label className='form-label' for='email'>
Email
</Label>
<Controller
id='email'
name='email'
control={control}
render={({field}) => (
<Input type='text' id='email' name='email' autoFocus invalid={errors.email && true} {...field} />
)}
/>
{errors && errors.email && <FormFeedback>{ errors.email.message }</FormFeedback>}
</div>
<Button color='primary' disabled={isSubmitting} block>
{isSubmitting ? <Spinner size='sm' /> : 'Send reset link'}
</Button>
</Form>
reactjs
react-redux
react-hooks
webforms
use-form
0 Answers
Your Answer