[Explained] Cannot read property 'setstate' of undefined / Needs improvements

posted 6 min read

You may have encountered the error "Cannot read property 'setstate' of undefined" while working with react when dealing with context.  Wrong understanding of context especially in javascript classes will result in the error above especially when dealing with the"this" keyword in javascript class methods. This error can be solved by either introducing the "bind" method in the class constructor or replacing the function with an arrow function.In this Post we will go over the causes of this error and how to fix it using relevant examples.

Uncaught TypeError: Cannot read properties of undefined (reading 'setState') (Explanation)#

To better understand this problem, let us analyze the error message. New react programmers who don't understand javascript context will most probably encounter this error while using classes  while writing react code. This normally happens when trying to access the "this" keyword inside a method that  has not been bounded to it in terms of the keyword's  context.

To better understand this lets look at an example


import React, {Component} from 'react'

class App extends Component{
constructor(props);{
super(props)
this.state = {
username: "anonymous",
}
}

updateUsername(){
// the bellow code will raise the error because this is undefined inside this method
this.setState({username: "admin"})
}

render(){
console.log(this.state.username);
return (



)
}
}
export default App;
NOTE: .in the above example we have created an updateUsername method which we has not bounded the context of the keyword "this"

In the above code since the method has not been bounded to the this keyword it results to undefined  which raises the error as shown below.


$ Uncaught TypeError: cannot read properties of undefined (reading 'setState') 

Reasons that will cause this error #

The js react error will be raised when context to this keyword is not properly bounded to a class method. From the example above it is clear that the error is as a result of the this keyword returing "undefined" as a value and we clearly know that "undefined" has no property setState.

Caution: trying to access property setState of "undefined" variable will result to an error. It is illegal in the javascript syntax.

The Solution #

First of all it is essential to understand  javascript context using classes which in turn will make it  easier to avoid all sorts of context issues.

To solve this problem we can replace the updateUsername function  to using an arrow function which will solve your issues automatically.

The other way is by using the bind method on the constructor function

Lets see how we can do this below

Solution one(Arrow Function)

By modifying the updateUsername function to using an arrow function we can fix the problem easily without introducing complexities

Lets correct the above example by replacing the updateUsername function to an arrow function


import React, {Component} from 'react'

class App extends Component{
constructor(props);{
super(props)
this.state = {
username: "anonymous",
}
}

updateUsername = () => {
// updateing to arrow funciton corrects the issue
this.setState({username: "admin"})
}

render(){
console.log(this.state.username);
return (



)
}
}
export default App
Tip: Arrow functions are recommended over the normal functions where applicable. The code looks cleaner and better to understand

Running the above code using the arrow function will solve this issue. This is because the "this" keyword of the enclosing scope is specific to the component instance whie using arrow functions

Solution two(using "bind" method)

Another way of solving this problem is the use of the bind method on the function in the constructor of the class.

Let's see the updated code:


import React, {Component} from 'react'

class App extends Component{
constructor(props);{
super(props)
this.state = {
username: "anonymous",
}
// add binding method here
this.updateUsername = this.updateUsername.bind(this)
}

// works after binding
updateUsername(){
this.setState({username: "admin"})
}

render(){
console.log(this.state.username);
return (



)
}
}
export default App;

In the above code we have added the "bind" method in the constructor. This method adds and returns a new function where the correct value is assigned on the "this" keyword. We can then use the bounded version anywhere inside the class body :

 

The Conclusion

Thank you for sticking to this tutorial all through. We have seen how to properly use the this keyword in react using the correct context to prevent the this keyword from returning an "undefined" value which results to the error above. We have seen how to replicate the issue, the causes and how to fix the issue. We have discussed two approaches of fixing, using the arrow function(recommended since its cleaner) and declaring a bound method in the constructor class. I hope you better understand the problem when you encounter it. Happy Hacking

 

1 Comment

1 vote

More Posts

Cannot read property '0' of undefined (Javascript)

Aulia Ika Savitri - May 11

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelskiverified - Apr 23

5 Web Dev Pitfalls That Are Silently Killing Your Projects (With Real Fixes)

Dharanidharan - Mar 3

The Audit Trail of Things: Using Hashgraph as a Digital Caliper for Provenance

Ken W. Algerverified - Apr 28

Google Drive Sync

Pocket Portfolio - Jan 5
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

3 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!