Magicked
Magicked

Reputation: 647

React async function is not a function

In one of my components I have the following functions:

addNewIndicator(attrs = {}) {
  const value = attrs.value || 'Indicator'
  const type = attrs.type || 'Generic Type'

  this.createIndicator(value).then(
    console.log('Indicator Created.')
  )
}

async createIndicator(value) {
  await this.props.createIndicatorMutation({
    variables: {
      value
    },
    update: (store, { data: { indicator }} ) => {
      const data = store.readQuery({ query: INDICATOR_FEED_QUERY })
      data.indicatorFeed.splice(0, 0, indicator)
      store.writeQuery({
        query: INDICATOR_FEED_QUERY,
        data,
      })
    }
  })
}

addNewIndicator() is triggered on a button click. When it runs, I get the following error:

TypeError: this.createIndicator is not a function

It is pointing to this line:

this.createIndicator(value).then(

I've done quite a bit of Googling, but haven't been able to figure out why this is the case. My understanding is that async functions can be called like that, but perhaps I'm missing something. Sorry if this is a silly question, I'm still learning React!

Also, I created the project using create-react-app and haven't modified it much other than adding some packages. Thanks for any help!

Edit to add how it is called. It is called from a child component props:

<Button primary onClick={this.handleAddSelectionClick}>Add Selected As Indicator</Button>

and handleAddSelectionClick:

handleAddSelectionClick = () => {
  ...snip...
  this.props.addNewIndicator({
    value: new_indicator_str,
  })
}

Upvotes: 0

Views: 1539

Answers (2)

L.E.
L.E.

Reputation: 170

try to validate that your 2 methods using the same context (this) - you might need to do something like that in the constructor:

this.addNewIndicator = this.addNewIndicator.bind(this);
this.createIndicator = this.createIndicator.bind(this);

Upvotes: 2

Kit Isaev
Kit Isaev

Reputation: 700

You probably just forgot to bind “this”. As you passed addNewIndicator as a callback, it lost its context. In this article several methods of binding callbacks are described, with all pros and cons of each. https://reactjs.org/docs/handling-events.html

Upvotes: 0

Related Questions