React JS Unexpected reserved word 'await'

Viewed 9108

I am struggling with this async await issue I have created async function and for that I am calling await but I am getting error Unexpected reserved word 'await' Below is the async function

export const addProductCall = async (product) => {
    let accessToken = window.localStorage.getItem("accessToken");
    await axios.post(SERVER_URI + '/inventoryservice/v1/item',
        product,
        { headers: { "Authorization": "Bearer " + accessToken, "Content-Type": "application/json" } })
}

Below is the function from where I am calling this function.

const handleSubmit = () => {
        const data = {
            'storeId': customerDetails.id, category, categoryToBeAdded, description,
            productCode, productName, sku, price, unit, quantity
        }
        await addProductCall(data);
    }
2 Answers

You cannot use the await keyword outside of an async function :

const handleSubmit = () => {
  const data = {
    'storeId': customerDetails.id, category, categoryToBeAdded, description,
      productCode, productName, sku, price, unit, quantity
  }
  await addProductCall(data);
}

should be :

const handleSubmit = async () => {
  const data = {
    'storeId': customerDetails.id, category, categoryToBeAdded, description,
      productCode, productName, sku, price, unit, quantity
  }
  await addProductCall(data);
}

Replace

const handleSubmit = () => {
     

with

const handleSubmit = async () => {
     

For await to work, it needs to be wrapped inside an async function

Related