0

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?

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
FabricioG
  • 3,107
  • 6
  • 35
  • 74
  • 2
    `this.resetThenSet = this.resetThenSet.bind(this);`. Also, consider checking this out: https://stackoverflow.com/a/48044643/4875631 – Blue Feb 05 '19 at 00:25
  • You can avoid binding by using arrow functions syntax as well. async resetThenSet = (id, arrayId, title) => { let size = [...this.state[arrayId]] //blah blah blah } – rpandey Feb 07 '19 at 21:26

2 Answers2

2
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()}
    />
...
Gavin Thomas
  • 1,827
  • 2
  • 11
  • 17
  • Avoid passing new closures to subcomponents. every time the parent component renders, a new function is created and passed to the input. This is a React component, this would automatically trigger it to re-render, regardless of whether its other props have actually changed. – rpandey Feb 07 '19 at 21:24
1
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

rpandey
  • 102
  • 5