merry-go-round
merry-go-round

Reputation: 4615

Why is my function is undefined?

TaskQueue: Error with task : undefined is not a function (evaluating 'this._renderReplies(replyCount)')

I'm getting this error above.

_renderReplies = (replyCount) => {
    return (<Text>`View ${replyCount} replies`</Text>);
}

_renderItem(row) {
           ...
        <View>{this._renderReplies(replyCount)}</View> <- Getting an error here
      </View>
    )
  }

Why am I getting undefined function error???? So weird.

Upvotes: 1

Views: 105

Answers (3)

AlexB
AlexB

Reputation: 3548

_renderItem does not have access to this. You can either use an arrow function or bind this inside the constructor. Arrow functions always have access to this.

Arrow functions method :

_renderItem = (row) => {
           ...
        <View>{this._renderReplies(replyCount)}</View> <- Getting an error here
      </View>
    )
}

_renderReplies = (replyCount) => {
    return (<Text>`View ${replyCount} replies`</Text>);
}

Bind method :

constructor(props) {
   this._renderItem = this._renderItem.bind(this)
   this._renderReplies = this._renderReplies.bind(this)
}

_renderItem(row) {
           ...
        <View>{this._renderReplies(replyCount)}</View> <- Getting an error here
      </View>
    )
}

_renderReplies(replyCount) {
    return (<Text>`View ${replyCount} replies`</Text>);
}

Upvotes: 2

Sagiv b.g
Sagiv b.g

Reputation: 31024

You should bind your _renderItem function to the class;

Either use an arrow function (like you did with _renderReplies) that will bind it automatically

_renderItem = (row) => {
           ...
        <View>{this._renderReplies(replyCount)}</View> <- Getting an error here
      </View>
    )
  }

Or bind it in the constructor:

constructor(props){
    super(props);
    this._renderItem = this._renderItem.bind(this);
}
_renderItem(row) {
           ...
        <View>{this._renderReplies(replyCount)}</View> <- Getting an error here
      </View>
    )
  }

Upvotes: 3

wyeo
wyeo

Reputation: 33

Try to not use the this keyword when you call _renderReplies()

Upvotes: 0

Related Questions