FabricioG
FabricioG

Reputation: 3320

react js async function in a class

I currently have a function called resetThenSet like so

resetThenSet = (id, arrayId, title) => {
  let size = [...this.state[arrayId]]
  blah blah blah
}

This resetthenSet method is called from my render method like so:

        <Dropdown
          title="Size"
          arrayId="selectProduct"
          list={this.state.selectProduct}
          resetThenSet={this.resetThenSet}
        />

Everything works. I need to use async to be able to have another method inside of there await. So I switch the resetThenset to this:

async resetThenSet(id, arrayId, title){
  let size = [...this.state[arrayId]]
  //blah blah blah
}

This gives me an error in my console.

Invalid argument passed as callback. Expected a function. Instead received: [object Promise]

This appears to be something related to scope so I figured I would just add binding for it:

this.resetThenSet = resetThenSet.bind(this);

This gives me the error

resetThenSet is not defined

Is there a simple way to change a fat arrow function to be an async function in react?

I checked this and it didn't help: How can I use async/await in a es6 javascript class?

Upvotes: 0

Views: 16086

Answers (2)

rpandey
rpandey

Reputation: 102

this.resetThenSet = this.resetThenSet.bind(this);

Try this, as you were binding to an undeclared function. That's why it was throwing error

You can read more about "why to bind the function to this" https://medium.freecodecamp.org/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb

Upvotes: 1

Gavin Thomas
Gavin Thomas

Reputation: 1867

class youDidntTellUs extends Component {

async resetThenSet(id, arrayId, title){
let size = [...this.state[arrayId]]
  //blah blah blah
}

render(){
return (
  <Dropdown
      title="Size"
      arrayId="selectProduct"
      list={this.state.selectProduct}
      resetThenSet={() => this.resetThenSet()}
    />
...

Upvotes: 2

Related Questions