Reputation: 6522
I have the following redux-form (6.5.0) source code:
class MyForm extends Component {
handleSubmit() {
console.log("Inside the handleSubmit of the MyForm Component where state is accessible", this.state.MyStateElement);
}
function render() {
return (
<<<< CHOICE 1: >>>>
<form onSubmit={handleSubmit(this.handleSubmit.bind(this))} >
<<<< CHOICE 2: >>>>
<form onSubmit={handleSubmit(submit)}>
{someFields}
</form>
);
}
}
function submit(values) {
console.log("submit function outside the MyForm Component where form values are accessible but the State is NOT accessible", values);
// values correspond to every checkbox, radio button inside MyForm
}
There is a MyForm component. It has a redux-form inside. Now there is a handleSubmit() function that is defined inside the react component. There is a submit() function that is defined outside the react component. Now I can enable either the CHOICE 1 or the CHOICE 2 definition for the form tag. If I enable the first one, the handleSubmit inside the react component is called. Here, I am able to access the this.state
but not able to access the individual fields inside the form (unless I could map each of the fields to a global state manually, which I could not do explicitly for the dozens of Fields that I have). If I enable the CHOICE 2, the values for all the fields are so correctly coming to the submit
function. But I am not able to access the this.state
inside the submit
function.
My question is: Is there a way to get the Field values as well as the this.state
in a handleSubmit/submit function ?
Upvotes: 2
Views: 2626
Reputation: 693
Another solution would be...
1) When you wrapping your form component with reduxForm
you specify onSubmit
option.
class myForm extends React.Component {}
export default reduxForm({
form: 'myForm',
onSubmit: function(values) { console.log('hello', values) }
})(myForm);
2) This function is available inside component as this.props.handleSubmit
so you still can write your own submit handler and call this.props.handleSubmit
inside it.
class myForm extends React.Component {
myOwnSubmitHanlder() {
console.log('hello', this.state);
this.props.handleSubmit()
}
render() {
return (
<form onSubmit={this.myOwnSubmitHanlder}></form>
)
}
}
Upvotes: 1
Reputation: 6522
Okay, I found a solution (not sure if this is the best though). I just had to add the values parameter to the handleSubmit
function. So the updated source will be:
class MyForm extends Component {
handleSubmit(values) {
console.log("State:", this.state.MyStateElement);
console.log("Form values:", values);
}
function render() {
return (
<form onSubmit={handleSubmit(this.handleSubmit.bind(this))} >
{someFields}
</form>
);
}
}
Upvotes: 2