[Vuejs]-Function returns undefined in Vue.js

3πŸ‘

I found a solution, maybe it’s not the best but we can return data in a promise , something like

methods: {
    bsBooks: () => {
      return axios
        .get(
          "https://api.nytimes.com/svc/books/v3/lists/best-sellers/history.json?api-key=my_api_key"
        )
        .then(response => response.data.results)
    }
  },
  mounted() {
    this.bsBooks().then(value => console.log(value))
  }

0πŸ‘

The bsBooks() is undefined so use this.bsBooks(),
also store result into data named books and use it:

<template>
    <ul>
        <li v-for="book in books">{{ book }}</li>
    </ul>
</template>

data(){
    return {
        books: []
    }
}, 
methods: {
    bsBooks: () => {
        axios
            .get(
                "..."
            )
            .then(res => {
                return this.books = res.data.results
            });
    }
},
mounted() {
    this.bsBooks();
}

Leave a comment