Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React this.state is undefined?

Tags:

reactjs

I am following a beginner tutorial from Pluralsight, on form submit a value is passed to addUser component method and I need to push userName to this.state.users but I get error

 App.jsx:14 Uncaught TypeError: Cannot read property 'users' of undefined 

Component

import React from 'react' import User from 'user' import Form from 'form'  class Component extends React.Component {     constructor() {         super()         this.state = {             users: null         }     }     // This is triggered on form submit in different component     addUser(userName) {          console.log(userName) // correctly gives String         console.log(this.state) // this is undefined         console.log(this.state.users) // this is the error         // and so this code doesn't work         /*this.setState({             users: this.state.users.concat(userName)         })*/     }     render() {         return (             <div>             <Form addUser={this.addUser}/>             </div>             )     } }  export default Component 
like image 419
Ivan Topić Avatar asked Sep 01 '17 10:09

Ivan Topić


1 Answers

When you call {this.addUser} , it gets called, here this is an instance of your class(component), and thus it gives no error to you because addUser method does exist in your class scope, but when you are under addUser method you are using this to update the state which exist in the scope of class(component), but currently you are within the scope of addUser method and so it gives you an error as under addUser Scope you got nothing like state, user etc. So to deal with this problem you need to bind this while you are calling addUser method.So that your method always knows the instance of this.

So the final change in your code will look like this:-

<Form addUser={this.addUser.bind(this)}/> 

OR


You can bind this in the constructor,because it is the place when you should intialize things because constructor methods are called first when the components render to the DOM.

So you can do it in this way:-

  constructor(props) {     super(props);     this.state = {         users: null     }     this.addUser=this.addUser.bind(this); } 

And now you can call it in normal way as you did before:-

<Form addUser={this.addUser}/> 

I hope this will work,And I made it clear to You.

like image 115
Vinit Raj Avatar answered Sep 23 '22 14:09

Vinit Raj