I am using redux-form
to handle form data inside redux.
I have noticed that in order to use the syncErrors
state, to check for validation errors, I need to first check that the actual redux-form
has finished rendering, otherwise React will complain that it cannot find syncErrors
of undefined - implying that this.props.accountForm
, the redux-form
, is not yet available.
Is this the expected behavior?
This is the code that breaks:
render() {
return (
<SignUpInForm>
<div>
<Field
name="name"
component={renderTextField}
label="Full Name*"
/>
</div>
<div>
<Field
name="email"
component={renderTextField}
label="Email Address*"
/>
</div>
<div>
<Button
disabled={!!this.props.accountForm.syncErrors}
onClick={this.signUp}
>
Save
</Button>
</div>
..
</SignUpInForm>
)
}
And this is the code that works:
render() {
return (
!!this.props.accountForm && (
<SignUpInForm>
<div>
<Field
name="name"
component={renderTextField}
label="Full Name*"
/>
</div>
<div>
<Field
name="email"
component={renderTextField}
label="Email Address*"
/>
</div>
<div>
<Button
disabled={!!this.props.accountForm.syncErrors}
onClick={this.signUp}
>
Save
</Button>
</div>
..
</SignUpInForm>
)
)
}
To me, this looks a bit ugly!
Note - this is how I am connecting it to the reducer:
const mapStateToProps = state => {
return {
accountForm: state.form.accountForm
};
};
Account = connect(
mapStateToProps,
null
)(Account);
export default withRouter(
reduxForm({
form: "accountForm",
validate
})(Account)
);
Then the combineReducers file looks like this:
import { combineReducers } from "redux";
import { reducer as reduxForm } from "redux-form";
export default combineReducers({
form: reduxForm
});
All this time I was validating the redux-form
wrong!
I solved this by using the following redux-form
props to check for errors:
const { invalid, submitting } = this.props;
Then in the submit button I do something like this:
<Button
disabled={invalid || submitting }
onClick={this.signUp}
>