Matthew Gilbride
Matthew Gilbride

Reputation: 43

redux-form: ordering connect and reduxForm calls - can't access store props and syncErrors together

I have an issue that has been discussed here: https://github.com/erikras/redux-form/issues/3424

I basically have 2 requirements:

  1. I need to be able to access some of the props mapped into my component via mapStateToProps, in the onSubmit function from reduxForm.
  2. I also want to access the syncErrors value from my form state, inside MyFormComponent. This is in order to e.g. summarize the errors.

I try to accomplish this as follows:

const mapDispatchToProps = (state, ownProps) => ({
  data: state.dataFromServer // some data from the server
  syncErrors: getFormSyncErrors('myForm')(state),
});

const myFormSubmit = (values, dispatch, props) => {
  // need to access the data prop from above
}

const FormContainer =
  connect(
    mapStateToProps,
    mapDispatchToProps,
  )((reduxForm({
    form: 'myForm',
    onSubmit: myFormSubmit,
  })(MyFormComponent)));

The problem is as follows:

If I order this as above (connect wraps reduxForm), I have access to my prop from the store in myFormSubmit, but the syncErrors do not get passed down to MyFormComponent, so I cannot access them.

If I switch the order (reduxForm wraps connect), I have access to syncErrors in MyFormComponent, but don't have access to the prop from the store inside the myFormSubmit function (because it hasn't been mapped in yet, naturally).

Any suggestions on how to handle this?

I'd really prefer not to have to do this in MyFormComponent: Redux-form handleSubmit: How to access store state?

Upvotes: 4

Views: 1385

Answers (1)

gustavohenke
gustavohenke

Reputation: 41440

I think there's nothing wrong with wrapping with connect twice:

const addDataProp = state => ({
  data: state.dataFromServer // some data from the server
});

const addSyncErrorsProp = state => ({
    syncErrors: getFormSyncErrors('myForm')(state),
});

const FormContainer = connect(addDataProp)(
  reduxForm({
    form: 'myForm',
    onSubmit: myFormSubmit,
  })(
    connect(addSyncErrorsProp)(MyFormComponent)
  )
);

I had to over-indent the code above to make reading it easier :P I recommend you to use some compose()-like util instead

Upvotes: 5

Related Questions