React Redux - Why can't I easily set initialValues from this.props?

Viewed 406

So I've inherited a project in which I need to utilize FieldArrays to create a dynamic list of items. The "form" that it's in is not actually in a <form>, so therefore I've had to section off my FieldArrays code into its own component in order to let redux magically make it "work" to do the things I want it to do, such as prepopulate the fields with data, be able to add/remove fields easily, etc.

The problem is that I can't seem to pre-populate the component with the props from the higher up component so that the redux FieldArray can pick it up, no matter what I've tried.

Here is my code:

renderFlooring({ fields, meta: { touched, error, submitFailed } }) {

      return (
        <div>
          <div>
            <div className={styles.flooringHeading}>
              <h3> Site Specifications </h3>
              <button type="button" className={styles.add} onClick={() => fields.push({})}>Add Square Footage</button>
            </div>
            {(touched || submitFailed) && error && <span>{error}</span>}
            {fields.length === 0 &&
              <p className={styles.noFlooring}>No square footage or flooring type has been added.</p>
            }
          </div>
          <ul className={styles.sqFtList}>
            {fields.map((flooring, index) =>
              <li className={styles.card} key={index}>
                <div className="page-form__block">
                  <p> Estimate the total area of work in square feet </p>
                  <Field name={`${flooring}.square_footage`} onChange={this.changeFlooringSquareFootage} component={TextField} hintText="Square Feet" />
                </div>
                <div className="page-form__block">
                  <p> Enter Floor Type </p>
                  <Field name={`${flooring}.flooring_type`} onChange={this.changeFlooringType} component={TextField} hintText="Floor Type (VCT, Carpet, Vinyle)" />
                </div>
                <button
                  type="button"
                  title="Remove"
                  className={styles.remove}
                  onClick={() => {
                    fields.remove(index);
                    this.props.removeFlooring(index);
                  }}>Remove</button>
              </li>
            )}
          </ul>
        </div>
      );
    }



  render() {
    return (
      <FieldArray name="flooring" component={this.renderFlooring}/>
    );
  }
}

export default reduxForm({
  form: 'manageSquareFootageForm',
  initialValues: this.props.flooring
})(ManageSquareFootageForm);

The component in which this particular component is imporated looks like this:

<ManageSquareFootageForm
   changeFlooringType={this.changeFlooringType}
   changeFlooringSquareFootage={this.changeFlooringSquareFootage}
   removeFlooring={this.removeFlooring}
   flooring={this.props.flooring}
/>

I've even tried adding initialValues on my <ManageSquareFootageForm> but that ends up causing my fields.push({}) functionality to stop working.

My data looks like the following:

[
   {square_footage: "500", flooring_type: "carpet"},
   {square_footage: "1000", flooring_type: "carpet"}
]

Is there anything I can do here that's straight-forward?

Thanks in advance!

1 Answers

It happens because reduxFrom HOC is unaware of the component props, you do set the initialValues from prop like

const FootableForm = reduxForm({
  form: 'manageSquareFootageForm'
})(ManageSquareFootageForm);

export default connect((state, props) => ({
    initialValues: props.flooring 
  }))(FootableForm)

However, your Field are not generated on the initial load and hence won't get populated, you would rather make use of change function from ReduxForm update the values.

const defaultValues = { square_footage: "500", flooring_type: "carpet" }


class FieldArraysForm extends React.Component {
  componentDidUpdate(prevProps) {
    const {flooring, change} = this.props;
    const {flooring: prevflooring} = prevProps;
    console.log(JSON.stringify(flooring));
    // Do nothing if no flooring, or no change to flooring
    if (!flooring || flooring === prevflooring) {
      return;
    }

    if (!prevflooring || flooring.length > prevflooring.length) {
      change('flooring', flooring.slice(0, flooring.length - 1).concat(defaultValues));
    }

  }
  render() {
    const { handleSubmit, pristine, reset, submitting } = this.props;
    return (
      <form onSubmit={handleSubmit}>
        <FieldArray name="flooring" component={renderFlooring} />
      </form>
    );
  }
};


const FieldForm = reduxForm({
  form: 'fieldArrays', // a unique identifier for this form
  validate,
})(FieldArraysForm);

export default connect(state => ({
  flooring: (getFormValues('fieldArrays')(state) || {}).flooring
}))(FieldForm);

Check the working codeSandbox

Related