1

Using use object destructuring to destructe my state before sending a call to my REST API and it only works inside of an arrow function for me. I tried calling it inside of a regular function and I kept getting an error that it was undefined. Code examples are below

I'm calling the function in a child component, I'm not sure if that makes a difference. Your help would be greatly appreciated so I can learn this concept, thanks!

Code I don't understand why its breaking

async get() {
 const { userData } = this.state
 try {
  const response = await http.get('/v1', {
    userData
  })
  console.log('response', response);
  await this.setState({friends: response.data});
 } catch(err) {
  console.log("error getting friends ", err);
 }
}

**Code that works **

get = async () => {
 const { userData } = this.state
 try {
  const response = await http.get('/v1', {
    userData
  })
  console.log('response', response);
  await this.setState({friends: response.data});
 } catch(err) {
  console.log("error getting friends ", err);
 }
}
bzlight
  • 1,066
  • 4
  • 17
  • 43
  • `Async storage` is not valid JavaScript. The first is probably a method, the second is an async arrow function. You can only use `await` in an async function. So that's one reason why the first one does not work. The second reason is that [`this` works differently in arrow functions vs "normal" functions](https://stackoverflow.com/q/34361379/218196). Since you are using `this`, the behavior will be different. Nothing at all related to destructuring. Possible duplicate of https://stackoverflow.com/q/34361379/218196. – Felix Kling Mar 01 '19 at 00:12
  • Thanks @FelixKling! I actually didn't clean up my code as well as I should when I copied it in. I just updated the post to include the proper code. I get that error even when its an async function and Async Storage (which I had commented out in my code) isn't there. – bzlight Mar 01 '19 at 00:16
  • 1
    That still leaves the `this` difference. That will be the reason. See the linked question. – Felix Kling Mar 01 '19 at 00:17

1 Answers1

0

I think your code won't work because of this keyword. Understanding this keyword in javascript

To make it works. You can bind the method in the constructor of the class. For example.

class Example {

  constructor(){
    // ...
    this.get = this.get.bind(this); // Or bind the method that you call get method
  }

  async get() {
   const { userData } = this.state
   try {
    const response = await http.get('/v1', {
      userData
    })
    console.log('response', response);
    await this.setState({friends: response.data});
   } catch(err) {
    console.log("error getting friends ", err);
   }
  }
}
Tan Dat
  • 2,888
  • 1
  • 17
  • 39