-1
  • I have a class that uses class methods to call an API. The calls to the API return a Promise object.
  • When I call the class method on an instance of the class, and use .then, if my arrow function in the class method declaration points to a { }, I get a TypeError: Undefined error
  • This does not happen if my arrow function points directly to the API function I'm calling (just omitting the {} for the return block fixes the bug? Why?)
  • Is there some kind of variable scoping issue going on here that I'm not aware of?

The function that I call on the class instance: bar.doCreateUserWithEmailAndPassword.then(auth => {console.log(auth)}

WORKS AS EXPECTED:

class Foo extends Component{
  constructor() {this.auth = firebase.app.auth}
...
  doCreateUserWithEmailAndPassword = (email, password) => 
    this.auth.createUserWithEmailAndPassword(email, password)

TYPE ERROR:UNDEFINED:

class Foo extends Component{
  constructor() {this.auth = firebase.app.auth}
...
  doCreateUserWithEmailAndPassword = (email, password) => {
    this.auth.createUserWithEmailAndPassword(email, password)
  }
Z.M
  • 13
  • 2
  • What *exactly* is the error? – Pointy Mar 04 '20 at 17:23
  • 4
    You should `return this.auth.createUserWithEmailAndPassword(email, password)` with `{}`. – Roberto Zvjerković Mar 04 '20 at 17:24
  • `doCreateUserWithEmailAndPassword` doesn't return anything when you use `{}`. A bare `() => something` automatically returns the "body" of the bare arrow function. Using `{}` means you have to do it explicitly. – zero298 Mar 04 '20 at 17:25
  • 1
    Because without the `{}` javascript automatically inserts `return` before your code. But with the `{}` it does not insert a `return` keyword so you have to insert it yourself. So something like `(x, y) => foo()` is the same as `(x, y) => {return foo()}` – slebetman Mar 04 '20 at 17:27
  • Thanks! I feel really silly that this bug caused me an hour of headache because I forgot that there is no implicit return in { } arrow block. – Z.M Mar 04 '20 at 17:29
  • This is a duplicate of [When should I use `return` in es6 Arrow Functions?](https://stackoverflow.com/q/28889450/691711). – zero298 Mar 04 '20 at 17:29

1 Answers1

-2

With an one-line arrow function (no braces) the return is implicit. As soon as you add braces, you need to add the return statement, like this:

class Foo extends Component{
  constructor() {this.auth = firebase.app.auth}
...
  doCreateUserWithEmailAndPassword = (email, password) => {
    return this.auth.createUserWithEmailAndPassword(email, password)
  }
Josh Wulf
  • 4,171
  • 2
  • 16
  • 29