Ad

What's Causing This TypeError When Setting State?

- 1 answer

I'm trying to use fetch to get data from an api. The console log is giving me the correct json, but I'm getting the following error when trying to set state:

TypeError: Cannot read property 'setState' of undefined(…)

getInitialState() {
    return {
      checklist: {},
      documents: [],
      questions: [],
      faqs: [],
      hospitals: [],
      profile: {},
      guarantor: {},
    }
},

componentDidMount(){
    this.fetchUser(1);
    this.fetchFaqs();
},

fetchFaqs() {
    fetch(FAQ_API) 
        .then(function(response){
            return response.json();
        })
        .then(function(json){
            console.log("faqs: " , json);

            this.setState({
                faqs: json,
            });

        })
        .catch((error) => {
            console.warn(error);
        });

},
Ad

Answer

It looks like the reference to 'this' is no longer pointing to the correct place, try doing this:

fetchFaqs() {
var self = this;
    fetch(FAQ_API) 
        .then(function(response){
            return response.json();
        })
        .then(function(json){
            console.log("faqs: " , json);
            self.setState({
                faqs: json,
            });
        })
        .catch((error) => {
            console.warn(error);
        });
}

If you don't want to create the self variable, you could also refactor your promise return functions to es6 fat arrow functions, which would place this in the correct scope:

fetchFaqs() {
    fetch(FAQ_API) 
        .then((response) => {
            return response.json();
        })
        .then((json) => {
            this.setState({
                faqs: json,
            });
        })
        .catch((error) => {
            console.warn(error);
        });
}
Ad
source: stackoverflow.com
Ad