Dirk
Dirk

Reputation: 165

React component async await in other funtion

Quick question about async await, there are a lot of examples to use async await with React, but I have trouble to get it working.

componentDidMount = () => {

    const cards = mockCards;

    this.setState(
        {
            loading: false,
            cointrackerCards: [
                ...cards.map(
                    card => {
                        const price = await this.getCurrentSellPrice(card.coin, card.valuta, card.amount[card.coin])
                        return {
                            ...card, 
                            currentSellPrice: price
                        }
                    }
                )
            ]
        }
    )

}

getCurrentSellPrice = async (coinType, valuta, amount) => {
    //console.log(coinType, valuta, amount)
    try {
        const result = await coinbaseAPI.get('/prices/BCH-EUR/sell')
        //console.log(result.data.data)
        return result.data.data.amount
    }
    catch (err) {
        console.log('[ERRORHANDLER]', err)
    }
}

The above code throws a error: Syntax error: await is a reserved word (71:42) Directly calling the function in the currentSellPrice key, does not work either, as it returns a Promise. What am I doing wrong?

Upvotes: 0

Views: 145

Answers (2)

SAGAR RAVAL
SAGAR RAVAL

Reputation: 319

You are making two mistakes first is you didn't assign async keyword to the function. at cards.map.

anyways I guess it won't work even if you write it there because async await won't work in map use for in, for of or traditional for loop for doing this.

refer to this answer Using async/await with a forEach loop

Upvotes: 1

The Reason
The Reason

Reputation: 7973

Your problem: you can't awaiting something without async scope, this is what you do in/with componentDidMount. If you would like to use await inside componentDidMount mark it as async. Here is a working example of how it works:

class AsyncState extends React.Component {
  state = {
    flag: false
  }

  async componentDidMount(){
    const flag = await this.changeFlagAsync();
    this.setState({flag})
  }

  async changeFlagAsync(){
    return new Promise((resolve, reject) => { // simulate async
      setTimeout(() => resolve(true), 2000)
    })
  }

  render() {
    return <div>
      {this.state.flag && <div>Done after 2 sec</div> || <div>Waiting for promise</div>}
    </div>;
  }
}

Also working fiddle

Upvotes: 2

Related Questions