1

Learning VueJS and trying to do a simple API call on component load to put a list of repos onto my page. When I call and set the this.repos from the created() method, no problem. But if I set it as a method and then call it from this.getRepos nothing happens. No error, nothing. What am I missing about VueJS?

This works:

data: () => ({
    msg: 'Github Repos',
    ok: 'Im practically giving away these repos',
    repos: [],
  }),
  methods: {
  },
  async created() {
    const repos = await axios.get('https://api.github.com/orgs/octokit/repos');
    this.repos = repos.data.map(repo =>
      `<div class="box"><a href="${repo.html_url}">
        ${repo.name}
      </div>`,
    );
  },

This DOES NOT work:

data: () => ({
    msg: 'Github Repos',
    ok: 'Im practically giving away these repos',
    repos: [],
  }),
  methods: {
    getRepos: async () => {
      const repos = await axios.get('https://api.github.com/orgs/octokit/repos');
      this.repos = repos.data.map(repo =>
        `<div class="box"><a href="${repo.html_url}">
          ${repo.name}
        </div>`,
      );
    },
  },
  created() {
    this.getRepos();
  },

Any ideas? Thanks!

Anthony
  • 65
  • 1
  • 1
  • 6

2 Answers2

2

It's simply because you used arrow functions here so that this.repos's this is bound to window object. Changing async () => {} to async function() {} will help you overcome it.

See demo

Note that you should not use an arrow function to define a method (e.g. plus: () => this.a++). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.a will be undefined.

reference

tony19
  • 125,647
  • 18
  • 229
  • 307
choasia
  • 10,404
  • 6
  • 40
  • 61
0

Another way to do an Axios call with Vue using then() method:

demo

created() {
 axios.get('https://api.github.com/orgs/octokit/repos', {
   params: {
     type: 'all',
   },
 })
 .then((res) => {
   console.log('Success Response', res.data);
   res.data.forEach((repo) => {
     this.repos.push({ name: repo.name, url: repo.html_url, language: repo.language });
   });
 })
 .catch((err) => {
   console.log('Error', err);
 });
},
A_A
  • 310
  • 4
  • 13