Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I'm unable to set error to formik field using setFieldError or setError?

I'm using formik in my React Native App like this: In constructor this.myRef = React.createRef();

Creating my form component is like this

<AppForm
    innerRef={this.myRef}
    initialValues={{ currentPassword: '', newPassword: '', confirmPassword: '' }}
    validationSchema={validationSchema}
    onSubmit={() => ''}
    >

    <AppFormField
        heading='Current Password'
        name='currentPassword'
        autoCapitalize='none'
        secureTextEntry={!showCurrentPassword}
        icon={showCurrentPassword ? 'eye' : 'eye-off'}
        onIconClick={() => this.setState({ showCurrentPassword: !showCurrentPassword })}
    />
    
</AppForm>

Where AppForm is my custom formik form component and AppFormField is a custom component.

(I'm using ref bcz I'm submitting the form using Save button outside the form component)

Calling handle submit like this onBtnPress={() => this.handleSubmit()}

And finally the handleSubmit function where I want to set the error.

handleSubmit = async () => {

    this.myRef.current?.submitForm();
    this.myRef.current.setErrors({currentPassword: 'Hello'});
    this.myRef.current.setFieldError('currentPassword', 'Hello'); // I've tried both ways
    console.log('CurrentRef ', this.myRef.current);
}

I've tried both setErrors and setFieldError and expecting the formik to set the error "Hello" to the field 'currentPassword' but I'm unable to do so. Please tell me the mistake if any and tell me the correct way.

Thanks!

like image 628
Sanaullah Javeid Avatar asked Nov 15 '25 14:11

Sanaullah Javeid


1 Answers

Actually the problem was with the way I was calling the method. setFieldError and setErrors both are async and I was calling them without the await.

like image 84
Sanaullah Javeid Avatar answered Nov 18 '25 04:11

Sanaullah Javeid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!