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?

2
  • 2
    this.resetThenSet = this.resetThenSet.bind(this);. Also, consider checking this out: stackoverflow.com/a/48044643/4875631 Commented Feb 5, 2019 at 0: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 } Commented Feb 7, 2019 at 21:26

2 Answers 2

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()}
    />
...
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.