1

(Beginner here)

I'm trying to create an app in Vue.js that would let me interact with GitHub API. I tried to use vue-github-api at first, but because of troubles working with pagination I switched to octokat.js.

I tried to use the same template that was suggested in vue-github-api docs and just switch to the octokat.

For brevity I'll include this small sample:

<template>
  <div class="row">
    <div class="col-sm-3">
      <div class="panel panel-default">
        {{ user.name }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      userData: {},
      issuesList: {}
    }
  },
  mounted: function () {
    var Octokat = require('octokat')
    var octo = new Octokat({
      token: 'xxxxx'
    })

    octo.user.fetch(function (e, val) {
      this.userData = Object.assign({}, val)
      // or this.userData = val (not sure, which is correct)
    })
  },
  computed: {
    user: function () {
      if (this.userData) {
        return this.userData
      }
      return 'Uh-oh...'
    }
  }
}
</script>

<style></style>

What I'm getting is:

Uncaught TypeError: Cannot set property 'userData' of undefined

If I would do this:

this.userData = octo.user.fetch()

Then if i console.log it I get this:

[console.log output]

I just can't seem to be able to get the desired output out of the "fetch" command.

Has anybody dealt with something similar, or did you spot a glaring error?

Pakas
  • 47
  • 7
  • 2
    Try changing `octo.user.fetch(function (e, val) {` to an arrow function. Looks like this: `octo.user.fetch((e, val) => {`. – Wing Feb 27 '17 at 13:56
  • @wing It actually does the trick! How is it possible? – Pakas Feb 27 '17 at 14:10

1 Answers1

1

Let's look at the code fetching from the GitHub API:

octo.user.fetch(function (e, val) {
  this.userData = Object.assign({}, val)
  // or this.userData = val (not sure, which is correct)
});

Inside your callback function you are attempting to assign to this.userData however it is not working.

What you have to look at here is what is this referring to?

You are assigning this.userData inside the callback to octo.user.fetch. As a result this is not bound to your Vue instance – it would be bound to the function calling it or in your case undefined because the transpiler most likely added a 'use-strict' pragma.

What can I do about this?

In ES6 we have arrow functions. Arrow functions do not have this bound to it, therefore this is still referring to your Vue instance.

octo.user.fetch((e, val) => {
  this.userData = Object.assign({}, val)
});

Further reading

Wing
  • 8,438
  • 4
  • 37
  • 46
  • Thank you very much for the write-up! Funniest thing is that I started reading YDKJS some time ago, but I'm at the second book atm. Makes more sense now and will make much more when I finally get to the third book. – Pakas Feb 27 '17 at 14:33