Sri
Sri

Reputation: 2273

Vue axios get http not returning the response data

I have data.js importing axios and VueAxios as below:

When I am calling the getRecordTypes function in mutations(vuex) returns undefined. But when I do console log it returns the correct data set.

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

let BASE_URL = 'http://localhost:3000'
const API_URL = `${BASE_URL}/api/v1/`

export default {
  getRecordTypes () {
    let results = []
    let url = `${API_URL}record_types`
    axios.get(url).then((response) => {
      console.log(response.data) // return the actual arrary of data
      results = response.data
      return results
    }).catch(error => { console.log(error) })
  }
}

In my vuex mutations js file, I have imported the above data.js file like below:

import data from '@/lib/api/data'

export default {
  setRecordTypes (state) {
    console.log(data.getRecordTypes())  // return undefined
    state.recordTypes = data.getRecordTypes()
  }
}

I am new to Vue js and not sure what am I doing wrong?

Thanks in advance

Upvotes: 1

Views: 3547

Answers (2)

joaner
joaner

Reputation: 716

getRecordTypes() did't return anything, also is async function, actually return a Promise object.

All methods of axios return Promise object, rather than a direct result of response. If you understand the basics of async and Promise first, this will make learning easier :)

// data.js
export default {
  getRecordTypes () {
    let url = `${API_URL}record_types`
    // add return
    return axios.get(url).then((response) => {
      console.log(response.data) // return the actual arrary of data
      results = response.data
      return results
    }).catch(error => { console.log(error) })
  }
}

// mutations.js
import data from '@/lib/api/data'

export default {
  setRecordTypes (state) {
    // async
    data.getRecordTypes().then(results => {
      state.recordTypes = results
    })
  }
}

Upvotes: 4

96eleven
96eleven

Reputation: 116

Your result variable is defined with the 'let' keyword. That's means he is only available on the getRecordTypes scope level, so you can't re-assigned him in your axios promise.

You need to assign result in the resolve promise like this:

axios.get(url)
.then(response => {
  let result = [];
  result = response.data;
  console.log(result);
})

Upvotes: 0

Related Questions