0

I have the following code

import React, { Component } from "react";
import { Accounts } from "meteor/accounts-base";

export default class RegisterForm extends Component {
  registerUser(e) {
    e.preventDefault();
    Accounts.createUser(
      {
        email: this.email.value,
        password: this.password.value
      },
      error => {
        console.log(error);
      }
    );
  };

  render() {
    return (
      <form onSubmit={this.registerUser}>
        <input type="email" ref={input => (this.email = input)} />
        <input type="password" ref={input => (this.password = input)} />
        <button type="submit">Register User</button>
      </form>
    );
  }
}

Somehow, the function registerUser gives the following error

Uncaught TypeError Cannot read property value of undefined

when the form is triggered

But if I change it to :

  registerUser = e => {}

It seems to work. Why ? Thanks for the answer.

Alien
  • 11,017
  • 3
  • 29
  • 45
  • This might help you understand: [When should I use Arrow functions in ECMAScript 6?](https://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6) – ChrisR Jun 25 '18 at 12:35

1 Answers1

1

Because the latter syntax creates an arrow function that binds this like arrow functions usually do.

The former syntax just creates a "bare" function in the class.

class X {
  f() {
    console.log(this);
  }
  g = () => {
    console.log(this); 
  }
}

transpiles (roughly) to

var X = (function() {
  function X() {
    var _this = this;

    this.g = function() {
      console.log(_this);
    };
  }

  X.prototype.f = function f() {
    console.log(this);
  };

  return X;
})();
AKX
  • 93,995
  • 11
  • 81
  • 98