Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing this in onSubmit event handler with redux-form 6

I am trying to use my componenet props to call an action in submit event handler with redux-form 6.1.1 but in the event handler function I get "this" is undefined. here is what I do:

class ForgetPasswordForm extends Component {
  xubmit (values) {
    console.log(this);
  }

  render() {
    const { handleSubmit } = this.props;
    return (
      <form onSubmit={ handleSubmit(this.xubmit) }>
      ...
    );
  };
}

I also tried () => handleSubmit(this.xubmit.bind(this)) and this.xubmit.bind(this) as mentioned in React: this is null in event handler but none of them worked out.

Here is more details about my setup:

  • boilerplate: create-react-app v.0.5
  • react: v.15.3.2
  • redux: v.3.6
like image 588
Ali Ghanavatian Avatar asked Oct 18 '22 22:10

Ali Ghanavatian


2 Answers

handleSubmit.bind(this.xubmit) by this way inside the handleSubmit, this points to this.xubmit.

I also suggest you to read how bind works.

Note: I know only JavaScript

like image 68
Sunil B N Avatar answered Oct 27 '22 09:10

Sunil B N


Since you didn't provide your handleClick function I can only imagine that you have directly called the function passed in like handleClick (fn) { fn() } and this way you would have access to the context in that fn. Also you should pass a function to event handlers. Do something like this and see if it works:

onSubmit={this.props.handleSubmit.bind(this.props.context, this.xubmit.bind(this))}

You need to send parent component's context to your ForgetPasswordForm and bind handleSubmit to it to have access to that parent component's context and bind this.xubmit to this in order for it not to be undefined.

like image 42
MahdiPOnline Avatar answered Oct 27 '22 11:10

MahdiPOnline