Maihan Nijat
Maihan Nijat

Reputation: 9344

How to use async await with React componentDidMount() method?

I want to use async/wait with React componentDidMount() method but I am getting await is a reserved word error. I also tried wrap the statement in Immediate Invoked Function but it didn't help.

async componentDidMount() {
  this.geoLocation.getAddress().then(location => {
    if (location.address != null && location.error != "undefined") {
      let fifteenMins = [];
      await this.getFifteenMinsData(y, x).then(
        data => {
          fifteenMins = data["forecasts"];
        }
      );
        console.log(fifteenMins);
    } 
  });
}

If I remove the await keyword, then I get null in console.log, but if I do console log right before fifteenMins = data["forecasts"]; then I get data.

Related question: Await is a reserved word error inside async function

Upvotes: 3

Views: 4817

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074198

async functions always return promises. Since componentDidMount isn't designed/documented as an async function, React doesn't do anything with the promise it returns. If you use an async function for this, be sure to wrap all its code in try/catch so that all errors are caught and you don't end up with an unhandled exception (which becomes an unhandled rejection).

The problem is that you're trying to use await in a non-async function: The callback you've passed then. When using async/await, you almost never use then. Instead:

async componentDidMount() {
  try {
    const location = await this.geoLocation.getAddress();
    if (location.address != null && location.error != "undefined") {
      const data = await this.getFifteenMinsData(y, x);
      let fifteenMins = data["forecasts"];
      console.log(fifteenMins);
    } 
  } catch (err) {
      // Do something with the fact an error occurred
  }
}

Or avoiding returning a promise from componentDidMount by using an IIFE:

componentDidMount() {
  (async () => {
    const location = await this.geoLocation.getAddress();
    if (location.address != null && location.error != "undefined") {
      const data = await this.getFifteenMinsData(y, x);
      let fifteenMins = data["forecasts"];
      console.log(fifteenMins);
    } 
  })()
  .catch(error => {
    // Do something with the fact an error occurred
  });
}

Or don't use an async function at all (but async functions are really handy):

componentDidMount() {
  this.geoLocation.getAddress()
    .then(location => {
      if (location.address != null && location.error != "undefined") {
        return this.getFifteenMinsData(y, x)
          .then(data => {
            let fifteenMins = data["forecasts"];
            console.log(fifteenMins);
          });
      } 
    })
    .catch(error => {
      // Do something with the fact an error occurred
    });
}

Side note: This pair of lines:

const data = await this.getFifteenMinsData(y, x);
let fifteenMins = data["forecasts"];

can be written like this if you like, destructuring the result into the fifteenMins variable:

let {fifteenMins: forecasts} = await this.getFifteenMinsData(y, x);

Similarly, if you did decide to go with the non-async version, you can do that in the parameter list of the then handler:

.then(({fifteenMins: forecasts}) => {
  console.log(fifteenMins);
});

Upvotes: 8

Atul
Atul

Reputation: 430

if you are using await you dont have to use then

let data=  await this.getFifteenMinsData(y, x);

edit

let location = await this.geoLocation.getAddress();
  //do your stuff
  if (location.address != null && location.error != "undefined") {
    let fifteenMins = [];
    let data = await this.getFifteenMinsData(y, x);
    fifteenMins = data["forecasts"];
      console.log(fifteenMins);
  } 

Upvotes: 1

Related Questions