1

I'm trying to set a data object called types when I receive a response in the ready() method.

Like this:

export default {

  data () {
    return {
      types: null
    }
  }, 

  ready () {
   TypeService.showAll(1)
      .then(function(data) {
          this.types = data.types
      });
  }
}

But I receive the following error in the console:

 Cannot set property 'types' of undefined(…)

But when I console.log like this:

 ready () {
   TypeService.showAll(1)
      .then(function(data) {
          console.log(data);
      });
  }

It's not empty!?!?

enter image description here

What is going on here? It drives me crazy.

--EDIT--

TypeService.showAll(1)  
         .then(({ data }) => ({
            this.types: data.types
          }.bind(this)));
0

2 Answers 2

3

The issue is this.types, not data.types (which the JS error message doesn't make entirely clear).

  ready () {
   TypeService.showAll(1)
      .then(function(data) {
          this.types = data.types
      });
  }

this is not what you're expecting within the function here (it's not the Vue component). This should do the trick:

  ready () {
   TypeService.showAll(1)
      .then(function(data) {
          this.types = data.types
      }.bind(this));
  }
Sign up to request clarification or add additional context in comments.

1 Comment

@Jamie I'm not certain. The new ES6 syntax isn't something I've fully adopted yet.
2

Try

ready () {
var _this = this
TypeService.showAll(1)
  .then(function(data) {
      _this.types = data.types
  });
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.