gileneusz
gileneusz

Reputation: 1485

vuejs fetching api request and .then() function not working correctly

I'm fetching api request via basic fetchSpecialityArray() function:

  fetchSpecialityArray(){
    this.$http.get('http://127.0.0.1:8000/api/speciality')
      .then(response => response.json())
      .then(result => this.specialityTest = result).then(this.checkSpeciality())
  },

then in checkSpeciality() method I'm checking if this request is complete:

  checkSpeciality(){
      console.log('check if complete and show array: ')
      console.log(this.specialityTest)
  },   

Unfortunately I've got empty array in my console. When I trigger fetchSpecialityArray() method again I've got correct response in console.

What is the cause of this behaviour and how should I correct my code to make this work?

Upvotes: 1

Views: 1194

Answers (2)

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

Then require a function, here you pass a function that you invoke. You should invoke the function into the callback function as you can see int the following code:

.then(() => this.checkSpeciality())

Otherwise, you can pass the function without invoking it.

.then(this.checkSpeciality)

Upvotes: 1

Quentin
Quentin

Reputation: 943142

then(this.checkSpeciality())

You are calling this.checkSpeciality immediately and then passing its return value (undefined because there is no return statement) to then().

You need to pass a function to then().

Since this.checkSpeciality makes use of this you need to capture the correct value of this too. You can use bind to create a function which will all checkSpeciality with the correct value of this.

.then(this.checkSpeciality.bind(this))

Upvotes: 3

Related Questions