Arian
Arian

Reputation: 7719

I cannot use initialValues for redux-form, what should I do?

I want to render two redux form Fields in my component.

I have some initial values for those fields that come from a call to the server. But I cannot use initialValues in mapStateToProps.

Why? because my app state is an array of entities, and it's in the component where I have access to this.entityId which lets me choose the right entity from that array. In the mapStateToProps I don't have access to this

What should I do in this case?

class ShowGroup extends Component {
  constructor(props) {
    super(props);
    this.groupId = this.props.match.params.id;
    this.state = {
      loading: true,
      error: null
    };
  }

  componentDidMount() {
    this.props.fetchGroup(this.groupId,
      () => this.setState({loading: false}),
      error => this.setState({loading:false, error: error})
    );
  }

  render() {
    let {props, state} = this;

    let group = props.groups[this.groupId];

    return (
      <div className="show-group">
        <form>
          <Field
            name="name"
            fieldType="input"
            type="text"
            component={renderField}
            label="Name"
            validate={validateName}
          />
          <Field
            name="description"
            fieldType="textarea"
            component={renderField}
            label="Name"
            rows="2"
            validate={validateName}
            onBlur={this._updateGroupDesc}
          />
        </form>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    groups: state.groups
  };
}

const mapDispatchToProps = (dispatch) => {
    return {
        fetchGroup: (groupId, successCallback, errorCallback) => dispatch(fetchGroup(groupId, successCallback, errorCallback))
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(reduxForm({
  validate,
  enableReinitialize: true,
  form:'ShowGroup'
})(ShowGroup));

Upvotes: 0

Views: 48

Answers (1)

Denys Kotsur
Denys Kotsur

Reputation: 2599

You can use second parameter in mapStateToProps - ownProps.

So you can have access to your component's props in this function.

For example:

function mapStateToProps(state, ownProps) {
  const groupId = ownProps.match.params.id;

  return {
    groups: state.groups,
    initialValues: state.groups[groupId],
  };
}

Hope it will helps.

Upvotes: 2

Related Questions