Ed Lynch
Ed Lynch

Reputation: 623

Access state from render function

So I need to run this line of code:

var vehicles = this.state.vehicles;

In the render function:

render: function(){...}

I currently get this error:

Uncaught (in promise) TypeError: Cannot read property 'state' of undefined

Even though this line works:

this.setState({vehicles: json})

This is also part of the code:

getInitialState: function(){
    this.render = this.render.bind(this)
    return {
      vehicles: []
    }
}

How can I fix this error and access the data?

Upvotes: 4

Views: 19153

Answers (4)

Ivan Burnaev
Ivan Burnaev

Reputation: 2730

It seems to be a context bind problem.

Cannot read property 'state' of undefined

That means this is undefined. I guess you're using it in some change handler. Try to onChange={this.changeHandler.bind(this)}.

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281636

You don't bind the render function. I assume that you are creating a component using React.createClass since you are using getInitialState to initialise the state. With React.createClass, React automatically does the binding for you.

Even if you create a component by extending React.Component, render method and the lifecycle functions are automatically bound to the React Component context.

Your getInitialState function will simply be

getInitialState: function(){
    return {
      vehicles: []
    }
  }

A sample working snippet

var App = React.createClass({
    getInitialState: function() {
      console.log(this);
      return {count: 0}
    },
    render: function() {
      return <div>Count:{this.state.count}</div>
    }
})

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>

Upvotes: 4

Crysfel
Crysfel

Reputation: 8158

You need to define the initial state, it looks like you didn't, therefore you are getting that error.

class YourComponent extends PureComponent {
  state = {}; // <-- Initialize the state
}

Or using the constructor

class YourComponent extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {}; // <-- Initialize the state
  }
}

Or using ES5 (Deprecated)

var YourComponent = React.createReactClass({

  getInitialState: function() {
    return {};  // <-- Initialize the state
  },

  // ...

});

Upvotes: 3

Marko Gresak
Marko Gresak

Reputation: 8207

To use this.setState, you first have to declare the state variable on this reference inside your component.

You do that in the consturctor, like this:

constructor(props) {
  super(props);
  this.state = {...};
}

You can read more about local state in the React docs: Adding Local State to a Class.

Upvotes: 1

Related Questions