this.setState is not a function [duplicate]

You are losing the React class this context. Bind it, and also bind it in the async callback function too.

constructor(props){
    super(props);
    console.log("search box imported");
    this.state = {
        results:[]
    };
    this.searchGif = this.searchGif.bind(this);
}

searchGif(event) {
    // ... code here
    xhr.onreadystatechange = () => {
    // ... code here
        this.setState();
    }
}

awesome thing about arrow functions is they bind your context for you and the syntax is awesome too. downside is browser support. Make sure you have a polyfil or a compile process to compile it into ES5 syntax for cross browser performance.

If you cant do either of those then just make a shadow variable of your this context outside of the async onreadystatechange function and use it instead of this.


Edit

Most compilers these days handle binding methods to the class with arrows (without specifying babel transforms … etc), you can assign state as well this way without a constructor

export default class SearchBox extends Component {
  state = { 
    results: []
  }
  
  searchGif = (event) => {
    // ... code here
    xhr.onreadystatechange = () => {
    // ... code here
        this.setState();
    }
  }
  render() {
    // ...
  }
}

Leave a Comment