Reputation: 13
I'm attempting to use setState function to a method in my App class..
example of the current code:
addRandomContact() {
this.setState({
actors: contacts.slice(0, 6)
})
}
I am expecting my contacts array to change from a length of 5 to 6.
The error I am receiving is the following:
TypeError: Cannot read property 'setState' of undefined addRandomContact
Upvotes: 1
Views: 97
Reputation: 356
Though it's not very clear from your given codebase what is the issue but one possible error you could make is that you are not binding addRandomContact
inside constructor of that class component. Try to paste the following code in your constructor and check if it solves
this.addRandomContact = this.addRandomContact.bind(this);
Upvotes: 0
Reputation: 116
"this" keyword will not be accessible inside this function and hence its undefined. You have to use arrow function like below:
addRandomContact = () => {
this.setState({
actors: contacts.slice(0, 6)
})
Upvotes: 1