Yingqi
Yingqi

Reputation: 1525

`The 'async' modifier can only be used in TypeScript files.ts(8009)` error when using async in react.js

So when I try to add async/await in the react file, I got this error:

The 'async' modifier can only be used in TypeScript files.ts(8009)

Does that mean I cannot use async/await in React or that is a problem of vs code or what can I do to enable it?

Here is the whole file:

import React from 'react'
import Button from 'react-bootstrap/Button'
import {addOrder} from '../actions/orderAction'
import {connect} from 'react-redux'

class Dish extends React.Component{

    async handleClick = (dish) =>{
     this.props.addOrder(dish)
     localStorage.setItem("order", this.props.order)
     alert(`${dish.name} added to your order!`)
    }


    render(){
      let dish = this.props.dish  
        return(
        <div className="col-4">  
            <img />
            <h5>{dish.name}         ${dish.price}</h5>
            <Button onClick = {()=>this.handleClick(dish)} size="sm" variant="primary">Order</Button> 
        </div>
    )
  }
}

const mapDispatchToProps = dispatch =>{
    return {
        addOrder: (dish) =>dispatch(addOrder(dish))
    }
}

const mapStateToProps = state =>{
    return{
        order: state.order
    }
}


export default connect(null,mapDispatchToProps)(Dish)

Thanks!

Upvotes: 10

Views: 9529

Answers (3)

kartick shaw
kartick shaw

Reputation: 1013

For normal functions we put async keyword right before function name

async handleClick(dish) {   this.props.addOrder(dish)  
 localStorage.setItem("order", this.props.order)   alert(`${dish.name}
 added to your order!`) }

For lambda function we put aync keyword right before argument

 handleClick = async (dish) =>{
     this.props.addOrder(dish)
     localStorage.setItem("order", this.props.order)
     alert(`${dish.name} added to your order!`)
    }

Upvotes: 0

Abdul Mateen Shaikh
Abdul Mateen Shaikh

Reputation: 311

You can try either

async handleClick(dish) {
  this.props.addOrder(dish)
  localStorage.setItem("order", this.props.order)
  alert(`${dish.name} added to your order!`)
}

OR

handleClick = async(dish) => {
  this.props.addOrder(dish)
  localStorage.setItem("order", this.props.order)
  alert(`${dish.name} added to your order!`)
}

Upvotes: 25

Jon Jones
Jon Jones

Reputation: 1084

H\ve you tried this in settings.json

"javascript.validate.enable": true

Upvotes: 2

Related Questions