Search code examples
reactjsredux-form

Update redux form field from a callback


I'm trying to do this:

"redux-form": "6.0.0-rc.5", 
"react": "^15.3.1",
"react-dom": "^15.3.1",




addressUpdated(newAddress) {
    //TODO, tell Redux form that a value is now available!
    this.props.fields.address.onChange(newAddress.label);
}

address is a hidden field that should get a value once addressUpdated is called. I get an error

Uncaught TypeError: Cannot read property 'onChange' of undefined

Component is generated:

<Field id="address" name="address" type="hidden" component={fieldFactory} />



const fieldFactory = ({id, input, label, type, meta: { touched, error } }) => {
    if(type.match(/hidden/)){
        return(
            <div>
                <input id={id} {...input} type={type} />
                {touched && error && <span>{error}</span>}
        </div>
    );
  }
}

```

Any ideas?


Solution

  • If I understand correctly, you can no longer use fields in props with v6.

    Consider row-form.js:

    Row.propTypes = {
      change: PropTypes.func.isRequired, // this binds redux-form change action creator
      dispatch: PropTypes.func.isRequired
    }
    

    then your callback function would look like this:

    addressUpdated(newAddress) {
        this.props.dispatch(this.props.change('address', newAddress.label);
    }
    

    Beware that in v6 rc5 this is not working because of the bug, but it was fixed in 6.0.1.

    In order to get that to work in rc5 you should import global change action creator and dispatch it with your form name:

    import { change } from 'redux-form';
    
    Row.propTypes = {
      form: PropTypes.string.isRequired,
      dispatch: PropTypes.func.isRequired
    }
    
    addressUpdated(newAddress) {
       this.props.dispatch(change(this.props.form, 'address', newAddress.label);
    }
    

    API reference: http://redux-form.com/6.0.1/docs/api/Props.md/