React this.state is undefined?

Reactjs

Reactjs Problem Overview


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

Reactjs Solutions


Solution 1 - Reactjs

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.

Solution 2 - Reactjs

@Vinit Raj's approaches works perfectly - tho i prefer to use the arrow function syntax like so.

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

Using an anonymous function like this, you don't need to bind it anywhere.

Solution 3 - Reactjs

If you prefer using arrow function do this. The arrow function syntax as like below

addUser = event => { 
    const { value }  = event.target;
    console.log("value", value);
}

To prevent this function being called on every render or re-render you need to

Change

<Form addUser={this.addUser}/>

To

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

So that addUser gets called only when event is happened/triggered

Solution 4 - Reactjs

I had the same problem but my issue was trying to access this.state before the this.state = { ... } call finished. Was doing something like this this.state = { ...this.function1() } and function1 = () => { a: this.state.b }. Hope this helps someone

Solution 5 - Reactjs

In your case by declaring your function as a fat arrow function you add context and remove the requirement to bind to this. This works just the same as the other solutions but makes things a lot simpler to both write and read. Just change...

 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)
    })*/
}

to...

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)
    })*/
}

And everything else can stay the same.

Solution 6 - Reactjs

I don't think the other answers explain this very well. Basically the problem is that Javascript's this keyword is insane (MDN very generously says it "behaves a little differently in JavaScript compared to other languages").

The TL;DR is that this is not necessarily the class that the method is defined in. When you use this.addUser in your <Form> element, this is actually the Form object! I'm not sure why React does this - I can't really think why anyone would want that, but it's easy to verify. Just put console.log(this) in addUser and you'll find it is an instance of Form.

Anyway the solution is pretty simple - use an arrow function. Arrow functions make a copy of this at the point where they are defined. So if you put one in your render function, as other people have suggested:

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

Then when render() is run, this will refer to the Component object, the arrow function will make a copy of it, and then when it is run it will use that copy. It's basically a shorthand for this code (and this is what people used to do before arrow functions):

    render() {
        const that = this; // Make a copy of this.
        return (
            <div>
            <Form addUser={function() { return that.addUser; }}/>
            </div>
            )
    }

Also, as other people have mentioned, creating a new function every time you call your render function might have performance implications, so it is better to capture this once somewhere else. I think this is a better approach than what other people have suggested:

class Component extends React.Component {
    constructor() {
        super()
        this.state = {
            users: null
        }
    }
    // This is triggered on form submit in different component
    addUser = (userName) => { 
        this.setState({
            users: this.state.users.concat(userName)
        })
    }
    render() {
        return (
            <div>
            <Form addUser={this.addUser}/>
            </div>
            )
    }
}

But this is my first day using React, and I normally try to avoid using languages as completely barking as Javascript, so take all this with a pinch of salt!

Solution 7 - Reactjs

A good pattern is to bind a method to the class in the constructor function. See https://reactjs.org/docs/handling-events.html

import React from 'react'
import User from 'user'
import Form from 'form'

class Component extends React.Component {
    constructor() {
        super()
        this.state = {
            users: null
        }
  this.addUser = this.addUser.bind(this); 
  //bind functions which need access to "this"v in the constructor here. 
        
    }
    // 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

Solution 8 - Reactjs

The problem is in this context, so use

<form onSubmit={(event)=>this.addUser(event)}>
   // Inputs
</form>
addUser(event){
   event.preventDefault()
   // Code this.state 
}

Solution 9 - Reactjs

Simpley use async in function

addUser =async (userName) => { console.log(this.state.users) }

this will works fine

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIvan TopićView Question on Stackoverflow
Solution 1 - ReactjsVinit RajView Answer on Stackoverflow
Solution 2 - ReactjsFiltenborgView Answer on Stackoverflow
Solution 3 - ReactjsHemadri DasariView Answer on Stackoverflow
Solution 4 - ReactjsMarc Sloth EastmanView Answer on Stackoverflow
Solution 5 - Reactjsuser6506514View Answer on Stackoverflow
Solution 6 - ReactjsTimmmmView Answer on Stackoverflow
Solution 7 - ReactjsGreggory WileyView Answer on Stackoverflow
Solution 8 - ReactjsGilView Answer on Stackoverflow
Solution 9 - ReactjsQamarView Answer on Stackoverflow