react - uncaught typeerror: cannot read property 'setstate' of undefined

  • Last Update :
  • Techknowledgy :

and if you are using ES6 and above you can use arrow function, then you don't need to use bind() it The first solution is add a constructor to your component and bind your function like bellow: When using ES6 code in React always use arrow functions, because the this context is automatically binded with it You have to bind your methods with 'this' (default object). So whatever your function may be just bind that in the constructor.

This is our Splunktool team suggestion ✌, we tried and its working fine
class Counter extends React.Component {
    constructor(props) {
      super(props);
​
      this.state = {
          count : 1
      };
​
      this.delta = this.delta.bind(this);
    }
​
    delta() {
        this.setState({
            count : this.state.count++
        });
    }
​
    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.delta}>+</button>
            </div>
        );
    }
}

This is due to this.delta not being bound to this.

In order to bind set this.delta = this.delta.bind(this) in the constructor:

constructor(props) {
   super(props);

   this.state = {
      count: 1
   };

   this.delta = this.delta.bind(this);
}

For ES6+ (ES2015) you can also use the ES6+ arrow function (=>) to be able to use this.

delta = () => {
   this.setState({
      count: this.state.count + 1
   });
}

Suggestion : 2

When using ES6 code in React always use arrow functions, because this context is automatically binded. even after binding delta in the constructor. Bottom and position properties can be used ...READ MORE Implement Optical Character Recognition in Python

Uncaught TypeError: Cannot read property 'setState' of undefined

class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.delta}>+</button>
            </div>
        );
    }
}

so use this:

(videos) => {
   this.setState({
      videos: videos
   });
   console.log(this.state.videos);
};

instead of:

function(videos) {
   this.setState({
      videos: videos
   });
   console.log(this.state.videos);
};

Suggestion : 3

even after binding delta in the constructor. 78129/error-cannot-read-property-setstate-of-undefined Error Cannot read property setState of... In order to bind set this.delta = this.delta.bind(this) in the constructor:

I am getting the following error

Uncaught TypeError: Cannot read property 'setState' of undefined
2._
class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.delta}>+</button>
            </div>
        );
    }
}

This is due to this.delta not being bound to this.

In order to bind set this.delta = this.delta.bind(this) in the constructor:

constructor(props) {
   super(props);

   this.state = {
      count: 1
   };

   this.delta = this.delta.bind(this);
}

Suggestion : 4

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email. By continuing you agree to our Terms of Service and Privacy Policy , and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email. About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

1._
import React from "react";
import "./styles.css";
 
class App extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     input: ""
   };
 }
 
 handleChange(e) {
   this.setState({[e.target.name]: e.target.value})
 }
 render() {
   console.log(this.state)
   return (
     <div className="App">
       <h1>Sample React Application</h1>
       <input name="input" onChange={this.handleChange} value={this.state.input} type="text" placeholder="Type here..."/>
       <input type="submit" />
     </div>
   );
 }
}
 
export default App;
2._
handleChange(e) {
   console.log(this, "change")
   this.setState({
      [e.target.name]: e.target.value
   })
}
3._
render() {
   console.log(this, "render")
   return (
     <div className="App">
       <h1>Sample React Application</h1>
       <input name="input" onChange={this.handleChange} value={this.state.input} type="text" placeholder="Type here..."/>
       <input type="submit" />
     </div>
   );
 }
5._
handleChange = (e) => {
   this.setState({
      [e.target.name]: e.target.value
   })
}

Suggestion : 5

I am getting this error and am not able to load my data as a result even though it is there. This is the correct answer, the arrow function binds this for you so you can access it within the function and it will still point to the component. What is the error? Did the console print the correct data? Have you import axios? Can’t believe that worked and I was that stupid. I always use arrow functions because it eliminated the need to bind it but forgot it there.

1._
import React, { Component } from 'react'
import Comment from '../presentation/Comment';
import CreateComment from '../presentation/CreateComment';
import styles from '../layout/styles';
import Api from '../../utils/ApiManager';

class Comments extends Component {
	constructor() {
		super()
		this.state = {
			list: []
		}
	}
    // override this function
	componentDidMount(){
		console.log('Comments componentDidMount: ');
		Api.get('/api/comment', null, function(err, response) {
			if (err) { alert("Error: " + err); return;}
			
			console.log('RESULTS: ' + JSON.stringify(response.message));

            
            this.setState({
                list: response.message
            })
		})
	
	}
	

    submitComment(comment){
        console.log("Submitting comment" + JSON.stringify(comment));
        
        let updatedComment =Object.assign({}, comment);
        Api.post('/api/comment', updatedComment, (err, response) => {
            if(err) {alert(err); return;}
            
            let updatedList = Object.assign([], this.state.list);
            updatedList.push(response.message);

            this.setState({
                list: updatedList
            })
        })
        
    }
    
    
    render() {
        const commentStyle = styles.comment;
        const commentList = this.state.list.map((comment, i) => {
            return (
                <li key={i}><Comment currentComment={comment} /></li>
            )
        });
        return (
            <div>
                <h2>Comments for ...Zone [1]</h2>
                <div style={commentStyle.commentsBox}>
                    <ul style={commentStyle.commentList}>{commentList}</ul>
                </div>
                <CreateComment onCreate={this.submitComment.bind(this)} />
            </div>
        )
    }
    
}

export default Comments

I’m not sure if it’s related, but you need to pass props to both your constructor and super

constructor(props) {
   super(props)
   this.state = {
      list: []
   }
}

Oh, it’s so obvious now. You’re calling this.setState inside of your callback to Api.get(). You need to cache the reference to this outside of that API call.

componentDidMount() {
   let currentComponent = this;

   Api.get('/api/comment', null, function(err, response) {
      if (err) {
         alert("Error: " + err);
         return;
      }

      currentComponent.setState({
         list: response.message
      })

   })
}

You should use arrow function:

axios.get('https://swapi.co/api/people').then((response) => {

Suggestion : 6

Currently, you are calling bind. But bind returns a bound function. You need to set the function to its bound value. ~ Answered on 2015-08-31 18:19:32 In ES7+ (ES2016) you can use the experimental function bind syntax operator :: to bind. It is a syntactic sugar and will do the same as Davin Tryon's answer. Arrow functions capture the this value of the enclosing context [...]

even after binding delta in the constructor.

class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.delta}>+</button>
            </div>
        );
    }
}

This is due to this.delta not being bound to this.

In order to bind set this.delta = this.delta.bind(this) in the constructor:

constructor(props) {
   super(props);

   this.state = {
      count: 1
   };

   this.delta = this.delta.bind(this);
}

For ES6+ (ES2015) you can also use the ES6+ arrow function (=>) to be able to use this.

delta = () => {
   this.setState({
      count: this.state.count + 1
   });
}

Suggestion : 7

This issue is not related to this module. It is because your _renderActions does not have the right context (this). if you console.log this inside _renderActions you will have what is available on the global space (such as fetch, alert, ...) but not your component. A solution will be to simply bind your _renderActions function to your component context You can also use the arrow function syntax for your class methods in order to bind automatically.

1._
 _renderActions(props) {
        
      const options = {
        
        'Camera': (props) => {
          
          ImagePicker.openCamera({
              compressImageQuality : 0.8
          }).then(image => {
            this.setState({
                  source : image.path
              })
          });
        },
        'Photo': (props) => {
          
          ImagePicker.openPicker({
              compressImageQuality : 0.8,
              smartAlbums : ['UserLibrary','PhotoStream','Bursts']
          }).then(image => {
              this.setState({
                  source : image.path
              })
          });
        },
        'Cancel': () => {},
      };
      return (
        <Actions
          {...props}
          options={options}
          icon={()=>{return <Image source={{uri:'chat_photo',width:30,height:30}}/>}}
        />
      );
    }
2._
class YourClass extends Component {
   constructor() {
      super();
      this._renderActions = this._renderActions.bind(this);
   }