Currently, I am engaged in a project using nuxt js/vue js. The project requires me to interact with multiple REST APIs. To accomplish this task, I am utilizing the asyncData() function provided by nuxt js to make the API calls within the page component.
import { getCategories } from '~/api'
import { getProducts } from '~/api'
export default {
data() {
return {
}
},
asyncData ({ req, params }) {
//-----------------PART 1-----------------------------
// var res1 = getCategories()
// var res2 = getProducts()
// return {
// res1,
// res2
// }
//-----------------PART 2-----------------------------
// return getCategories()
// return getProducts()
//----------------------------------------------
},
created() {
if(typeof(Storage) !== "undefined"){
if(!localStorage.getItem("cityName")){
this.$router.push('/')
}
} else{
console.log('This browser does not support local storage')
}
this.$store.dispatch('initFilters')
this.$store.dispatch('initCategories', this.categories)
//NOTICE HERE
// console.log(this.allProducts) //This one works on single return
// console.log(this.res1.allProducts) //This doesnot work on object return
},
}
Upon trying to use return getCategories() or return getProducts() (as shown in PART 2 of the code), I successfully receive the desired object results. However, as I need both objects, I attempted to combine them into an object and return them (as seen in PART 1). Unfortunately, when calling console.log(this.res1.allProducts), I did not obtain the expected object.
The following is the API code segment:
import axios from 'axios'
const API_ROOT = 'http://deligram.mg/rest/'
const API_VERSION = 'V1'
const MAGENTO_STORE = 'default'
const API_BASE = API_ROOT + '/' + MAGENTO_STORE + '/' + API_VERSION + '/'
const apiUrl = (path) => {
return API_BASE + path
}
const apiGet = (path) => {
return axios.get(apiUrl(path))
}
export function getCategories () {
return apiGet('categories')
.then((res) => {
return { categories: res.data }
})
}
export function getProducts () {
return apiGet('products?searchCriteria%5BcurrentPage%5D=10')
.then((res) => {
return { allProducts: res.data }
})
}
If anyone can provide insight into what I might be doing incorrectly or suggest an alternative method to retrieve both objects simultaneously, it would be greatly appreciated.