Ed Lynch
Ed Lynch

Reputation: 623

setState not working

class Assets extends React.Component{

  constructor() {
    super();
    this.state = {
          assets: [],
          secondsElapsed: 0
        };
    }

tick() {
    if(start === true){

      fetch('/api/user/all/?name='+name, {credentials: 'include', method: 'get'}).then(function(data){
        return data.json();
      }).then( json => {
        this.setState({
            assets: json
          });
      });
      }
    }
  }

ReactDOM.render(<Assets />, document.getElementById('alerts'));

This code is throwing this error when run:

Uncaught (in promise) TypeError: Cannot read property 'setState' of null
    at eval (eval at <anonymous> (bundleAlerts.js:3430), <anonymous>:265:15)
    at <anonymous>

The code is been complied by webpack if that makes a difference. I was using the ReactCreate class before and it worked fine then but I changed it in an attempt to fix another error.

Thanks, Ed.

Upvotes: 0

Views: 449

Answers (1)

Win
Win

Reputation: 5584

Bind your tick function to your component. :) It was currently binded to the function and not to the class component therefore it could not access ‘this’, which means it won’t be able to access your props or state. You can either use the example below, autobind decorator (ES7) or transform class properties ‘tick = () => { ... }’.

class Assets extends React.Component {
  constructor() {
    super();
    this.state = {
      assets: [],
      secondsElapsed: 0
    };
    this.tick = this.tick.bind(this);
  }
  tick() {
    if (start === true) {
      fetch("/api/user/all/?name=" + name, {
        credentials: "include",
        method: "get"
      })
        .then(data => {
          return data.json();
        })
        .then(json => {
          this.setState({
            assets: json
          });
        });
    }
  }
  // ...rest of component
}

ReactDOM.render(<Assets />, document.getElementById("alerts"));

Upvotes: 1

Related Questions