Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set variable outside axios get [duplicate]

I can't return a value using this function because it is empty.

getNameById (id) {

    var name = ''

    axios.get('/names/?ids=' + id)
      .then(response => {
        this.response = response.data
        name = this.response[0].name
      })
      .catch(e => {
        this.errors.push(e)
      })
    // Is empty
    console.log('Name ' + name)
    return name
  }

How do I access the name variable inside "then" and return it?

like image 988
John Avatar asked May 28 '17 19:05

John


1 Answers

You should return the promise instead.

getNameById (id) {
  return axios.get('/names/?ids=' + id)
      .then(response => {
        this.response = response.data
        return this.response[0].name
      })
  }

and use it:

getNameById(someId)
  .then(data => {
    // here you can access the data
  });
like image 112
Ioan Avatar answered Oct 21 '22 07:10

Ioan