Golan Kiviti
Golan Kiviti

Reputation: 4245

redux-form - onSubmit doesnt work

I'm using redux-form and I just cant get the onSubmit fuction to work.

EDIT: My problem is that the function is not being called, i put debugger on the onSubmit and it doesnt get there. here is my form:

class userForm extends Component {
    onSubmit(values) { // do here something }
    render() {
        const { handleSubmit } = this.props;
        return <form onSubmit={handleSubmit(this.onSubmit)}>
            <Field name='id'
                component={TextField}
                label='id'/>
            <Field name='name'
                component={TextField}
                label='name' />
            <button type='submit'>Submit</button>
        </form>
    }
}

export default reduxForm({
    form: 'userForm'
})(userForm);

But it never gets to the onSubmit method.

What am I doing wrong?

Upvotes: 3

Views: 5458

Answers (2)

Phoenix
Phoenix

Reputation: 4274

you just need to add .bind keyword after submit,

class userForm extends Component {
onSubmit(values) { // do here something }
render() {
    const { handleSubmit } = this.props;
    return <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
        <Field name='id'
            component={TextField}
            label='id'/>
        <Field name='name'
            component={TextField}
            label='name' />
        <button type='submit'>Submit</button>
    </form>
    }
}

export default reduxForm({
    form: 'userForm'
})(userForm);

Upvotes: 3

alex
alex

Reputation: 5573

This is an edited version of the pattern I use.

Note the use of the bind keyword.

Generally I use redux to manage state, and would also use an action inside the function handleFormSubmit. But this should get you on the right track.

import React, { Component } from 'react';
import { reduxForm } from 'redux-form';

class Userform extends Component {

  static handleFormSubmit({ id, name}) {
    console.log({id, name});
  }

  render () {
    const { handleSubmit, fields: { id, name }} = this.props;
    return(
      <form onSubmit={handleSubmit(Userform.handleFormSubmit.bind(this))}>
        <fieldset>
          <label>Id:</label>
          <input {...id}/>
        </fieldset>
        <fieldset>
          <label>Name:</label>
          <input {...name} />
        </fieldset>
        <button action="submit">Submit</button>
      </form>
    );
  }
}


export default reduxForm({
  form: 'userform',
  fields: ['id', 'name']
})(Userform);

Upvotes: 0

Related Questions