4

I have a NetCore2 app with ReactJS installed.

My React app does something like this ->

  • User inputs into a field
  • axios makes a call to an api to get the user and/or list of users
  • The input field shows suggestions based on what was saved in PeopleList state.

I'm using Office Fabric UI React - People Picker (in case it matters).

My problem here is that i have no idea how i could use async/await in my code.

If i put something like this

async asynconFilterChanged = (filterText, currentPersonas, limitResults) => {

VS Code throws an error telling me that async is only for .ts files. Also if i use await in any other functions i will get an error such as await is a reserved word.

As far as i know async/await is not TS only...(or am i wrong?).

I'm using the older Babel with the ENV preset.

Let me know if i need to provide more code, but TLDR what i want is to only start the filter function after my axios is done pushing items into the PeopleList state (array of objects).

Thanks!

Dante R.
  • 902
  • 3
  • 13
  • 41

2 Answers2

15

When using an arrow function you should write async/await like this:

const asynconFilteredChanged = async () => {
 // code here 
}

Check out Syntax for async arrow function

Dmitriy
  • 1,211
  • 1
  • 11
  • 28
  • Seems to partially work, however babel still throws the "await is a reserved word" error even tho the "awaited" function has been transformed to async. Any tip on that? Also any idea where would be the best place to place the const function ? Would `render() {}` be ok? Thanks! EDIT: It seems moving it out of setTimeout stopped the "await" error. I assume you can't use await and timeout at the same time. – Dante R. Nov 22 '18 at 08:15
0

As per syntax try to follow above codebase,

asynconFilterChanged = async (filterText, currentPersonas, limitResults) => {
            try {
                await yourFucntion = (limitResults) => {
                ....Your logic...
                }
            } catch(error) {
                console.error(error);
            }

Yes, try to use and touch async-await guide

Anupam Maurya
  • 1,927
  • 22
  • 26