Call function after currentUserSync - Async Await issue

Viewed 172

I'm using react-native-google-signin. My code is:

async _setupGoogleSignin() {
  try {
    await GoogleSignin.hasPlayServices({ autoResolve: true });
    await GoogleSignin.configure({
      webClientId: '<from web>',
      offlineAccess: true
    });

    const user = await GoogleSignin.currentUserAsync()
      .then(this._someFunction(user));    // Is this correct? 
      console.log(user);        // this works. User is logged
  }

  catch(err) {
      console.log("Play services error", err.code, err.message);
    }
  }

_someFunction(user){

  console.log("ID: ",user.id)       // Error is thrown here

  this.setState({id: user.id});     // This is not set

}

With the .then(this._someFunction(user));, I want to pass the user to the function _someFunction.

The error is Play services error undefined Cannot read property 'id' of undefined.

I want to be able to call the function that sets the user when GoogleSignin.currentUserAsync() is completed. What am I doing wrong?

1 Answers

async..await is mixed with regular promise code, and not in a good way.

.then(this._someFunction(user)) is invalid, because then expects a function as an argument, and it receives undefined. Also, user is not defined at this point.

It should be

const user = await GoogleSignin.currentUserAsync();
this._someFunction(user);

This is exactly what async..await is for. To flatten the function and avoid thens when this is practical.

Related