-1

I'm trying to call a function from methods in mounted() but it returns undefined. If I make a console.log it shows the result. What I'm doing wrong?

 methods: {
    bsBooks: () => {
      axios
        .get(
          "https://api.nytimes.com/svc/books/v3/lists/best-sellers/history.json?api-key=mykey_is_here"
        )
        .then(res => {
          return res.data.results
        });
    }
  },
mounted() {
  console.log(bsBooks())
}
Grigore Budac
  • 1,351
  • 2
  • 15
  • 27
  • 1
    How do you know it returns undefined? You don't save returned value. Insert `console.log` inside `then` block to see what `res.data.results` is. You probably don't understand something about Promise vs synchronous functions. – Egor Stambakio Dec 25 '17 at 12:39
  • axios needs a url to get data from: https://alligator.io/vuejs/rest-api-axios/ – Nathaniel Flick Dec 25 '17 at 12:40
  • I tried the function in console log to see the returned value. I'm using an URL in axios. – Grigore Budac Dec 25 '17 at 13:17
  • axios get has to have a url: axios.get(`http://jsonplaceholder.typicode.com/posts`) – Nathaniel Flick Dec 25 '17 at 13:22
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JJJ Dec 25 '17 at 13:31
  • I've got a niggling feeling this is because of `bsBooks: () => {`. If you declare it like `bsBooks () {` and change your axios call to `return axios` does it help? – webnoob Dec 25 '17 at 14:03

2 Answers2

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))
  }
Grigore Budac
  • 1,351
  • 2
  • 15
  • 27
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();
}
talkhabi
  • 2,669
  • 3
  • 20
  • 29
  • nope, it doesn't work :) I tried something like that. I can use axios function directly in mounted, but I have one more function that checks some information and I think that is a better practice to divide those actions into functions. – Grigore Budac Dec 25 '17 at 13:20