Source:  Twitter logo

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!

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!`)
}
23 users liked answer #0dislike answer #023
Abdul Mateen Shaikh profile pic
Abdul Mateen Shaikh

H\ve you tried this in settings.json

"javascript.validate.enable": true

1 users liked answer #1dislike answer #11
Jon Jones profile pic
Jon Jones

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!`)
    }
0 users liked answer #2dislike answer #20
kartick shaw profile pic
kartick shaw

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).