Search code examples
react-nativeasync-awaitremote-debugging

React-Native async function unexpected identifier _this2


I have this function that I want to wait of the result of and then use it:

getUserId = () => {
    fetch("https://www.dummysite.com/mobile/person-id", {
      credentials: "include",
      method: "GET",
      headers: {
        Cookie: this.state.auth_token_res
      }
    }).then(res => {
      let id_obj = JSON.parse(res._bodyText);
      console.log("parsed json", id_obj);
      return id_obj.data;
    });
  };

I want to use it in this function:

async sendID() {
        let user_id = await this.getUserId();
        console.log(user_id);
        OneSignal.sendTags({
          user_id: user_id
        })
          .then(function(tagsSent) {
            // Callback called when tags have finished sending
            console.log("tag is set: ", tagsSent);
          })
          .catch(err => {
            console.log("error", err);
          });
  }

I don't see any syntax problems, and the app compiles, but when it starts it just hows this error:

error image

the other weird this is if i turn on remote debugging on this screen I get a different error: error 2

here is says that await is not in an async function but it is, and I am not getting syntax error in my editor or in the metro bundler.


Solution

  • There a few things you might have missed. Consider these changes. Although I didn't get a chance to test it, I am confident it will work or at least put you on a right track.

    getUserId = () => {
      // return fetch in order to await
      return fetch("https://www.dummysite.com/mobile/person-id", {
        credentials: "include",
        method: "GET",
        headers: {
          Cookie: this.state.auth_token_res
        }
      }).then(res => res.json());
    };
    
    // make this an arrow function
    sendID = async () => {
      try {
        let user_id = await this.getUserId();
        // after printing then decide what to do here;
        console.log(user_id);
    
        const tagsSent = await OneSignal.sendTags({
          user_id: user_id
        });
        console.log(tagsSent);
    
      } catch (err) {
        console.log(err);
      }
    
    }