How to fix Parsing error: Can not use keyword 'await' outside an async function

10,302

You need to have async keyword for the inner function

export function getData() {
  return async (dispatch) => {
    try {
      const data = await API.graphql(graphqlOperation(query))
      dispatch({ type: "DATA_AVAILABLE", data: data.data.listData.items });
    } catch(err) {
      console.log('error: ', err)
    }
  }
}
Share:
10,302

Related videos on Youtube

Skate to Eat
Author by

Skate to Eat

Updated on June 04, 2022

Comments

  • Skate to Eat
    Skate to Eat almost 2 years

    Getting a error message saying Parsing error: Can not use keyword 'await' outside an async function from below code for Redux action.

    What is the proper way to write this?

    export async function getData() {
      return (dispatch) => {
        try {
          const data = await API.graphql(graphqlOperation(query))
          dispatch({ type: "DATA_AVAILABLE", data: data.data.listData.items });
        } catch(err) {
          console.log('error: ', err)
        }
      }
    }
    
    • CertainPerformance
      CertainPerformance almost 5 years
      return (dispatch) => { is not async
    • AZ_
      AZ_ almost 5 years
      return async (dispatch) => { no need of async in export async function getData()
    • Skate to Eat
      Skate to Eat almost 5 years
      @CertainPerformance also tried export const getUserJournals = () => async (dispatch) => { ... } but didn't work :(
  • Skate to Eat
    Skate to Eat almost 5 years
    Thank you for the comment! the error message went away but still doesn't get the data from API...
  • Skate to Eat
    Skate to Eat almost 5 years
    Getting error: TypeError: dispatch is not a function
  • Radonirina Maminiaina
    Radonirina Maminiaina almost 5 years
    Updated my explaination
  • Radonirina Maminiaina
    Radonirina Maminiaina almost 5 years
    Updated my post
  • Skate to Eat
    Skate to Eat almost 5 years
    Getting Uncaught (in promise) TypeError: dispatch is not a function this time.
  • Radonirina Maminiaina
    Radonirina Maminiaina almost 5 years
    But you should pass dispatch as fucntion
  • Skate to Eat
    Skate to Eat almost 5 years
    It actually seems to be working when it on my dev environment with AWS amplify but does not working on my local. Not sure why lol
  • Shubham Khatri
    Shubham Khatri almost 5 years
    It may so be the case that qraphql query isn't working correctly in your local
  • Skate to Eat
    Skate to Eat almost 5 years
    Have any idea to debug that on my local?
  • Skate to Eat
    Skate to Eat almost 5 years
    This works! I had an issue somewhere else. Thank you for the answer.