Strange behavior observed with Nuxt Js asyncData method returning values

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.

Answer №1

Assuming the API methods return a Promise, it is recommended to utilize Promise.all for waiting until both promises are resolved. Then, you can combine all the data into one object that should be set by nuxt:

var res1 = getCategories()
var res2 = getProducts()
return Promise.all(re1, res2).then(function ([data1, data2]) {
 return Object.assign({}, data1, data2)
})

The resulting object will have the following structure:

{
  categories: [ /* data from getCategories() */]
  allProducts: [ /* data from getProducts () */ ]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Showing a gallery of images in React

I have a unique situation where I am working on setting a variable to match the import statement that calls for images. Once I have this variable assigned, I want to use it to display the corresponding image. For instance, if my code generates the name &ap ...

Printing without sufficient paper will result in an incomplete printout

https://i.stack.imgur.com/jNlRr.jpg I am facing an issue with printing the last column "Potensi". The text in this column is not fully printed. How can I resolve this problem? I am using PHP. Thank you ...

What is the proper way to detach an event listener from a class?

I am facing a challenge when trying to remove an event listener. After running the script, I receive an error message stating that changeGirl.off("click") is not a function. Despite this issue, everything else within the code is working perfectly fine. Any ...

Connect or disconnect an element to a JavaScript event handler using an anonymous function

I'm stuck on a basic issue... I have a custom metabox in my WordPress blog, and here's my event handler: jQuery('tr input.test').on('click', function( event ){ event.preventDefault(); var index = jQuery(this).close ...

Tips for setting up Nginx with Node.js on a Windows operating system

I am looking to set up Nginx on my Windows machine in order to run two node applications. Can anyone provide guidance on how to accomplish this? I have attempted to download Nginx 1.6.3, but have had trouble finding instructions specifically for running i ...

Generating output from a callback function in TypeScript

When I execute a graphql query, the showUsers function is supposed to display all users (styled as boxes). However, at the moment, nothing is showing up. I am utilizing a functional component instead of a class component. This function is invoked after m ...

Strategies for retaining additional fields added via JavaScript when the page is refreshed

var newField = document.createElement("lastExp"); newField.innerHTML = 'insert new form field HTML code here'; document.getElementById("lastExp").appendChild(newField); I have a button that adds an additional form field with a simple click. ...

Unable to retrieve innerHTML from a jQuery element

My current task involves implementing the Google Maps API. The code snippet below is what I have written so far: <div id="map"></div> To inspect the content of $("div#map"), I am utilizing the Google Chrome console. console.log($("div#map")) ...

Exploring the Power of Pythons, Selenium, and XPATH for Handling New Windows

Is it possible to retrieve an element through XPath after using the .click() method when that element is located within a section of JavaScript known as BODY_BLOCK_JQUERY_REFLOW and appears only after the click action? I am attempting to access this speci ...

Executing JavaScript functions when a browser tab is closed

When a user closes the browser tab, I want to call a specific JavaScript function. However, I only want this to occur when the user is actually closing the browser, not during page refreshes, link navigation, form submissions, or pressing the back button. ...

Develop a unique method for loading AngularJS templates

When working with AngularJS, there are various ways to provide an external template, such as using a script tag or a separate HTML file on the web server. However, I am faced with a situation where I need to implement a custom logic for retrieving these ...

Implementing a 1-second delay in a Vue.js delete request

I have items that are retrieved through API calls and users can add them to their cart. They also have the option to delete items from the cart, but I want the item to be visually removed from the front-end after 1 second because of an animation on the del ...

Creating dynamic transformations and animations for characters and words within a paragraph in 3D

Looking to add animation effects to specific parts of a paragraph, but transforming the entire box instead. Remembering seeing a solution on StackOverflow before, now regretting not saving it. Spent over an hour searching for a similar answer without succ ...

Encountered an error 'Unexpected token ;' while attempting to include a PHP variable in a jQuery AJAX call

Trying to execute a PHP script that updates a deleted field in the database when you drag a specific text element to a droppable area. Currently, here is the droppable area code: <div class="dropbin" id="dropbin" > <span class="fa fa-trash-o ...

Having trouble reaching the unidentified function

There are two different scenarios where the 3rd party library (BrowserPrint.js) is used; FUNCTIONAL ENV - JS and jQuery with the 3rd party libraries included simply in the <head> section of the document and the main function being called in $(do ...

Is it possible to alter the state just by clicking on the text?

I am currently facing a challenge in creating a select option for switching between notify and not notify status while using the regular text format preferred by my customer. The default value is set to notify, and upon clicking on the text it should chang ...

Developing a perpetually scrolling container within a webpage

I am attempting to implement a scrollable div on my webpage that can continuously load content. I am currently using the following code snippet for this --> http://jsfiddle.net/cyrus2013/Qq85d/ $(document).ready(function(){ function loadMoreContent() { ...

The font remains the same despite the <Div style=> tag

I have a script that loads external HTML files, but I am facing an issue with changing the font to Arial. The script is as follows: <script type="text/javascript"> $(document).ready(function(){ $("#page1").click(function(){ ...

Understanding the concept of hoisting in JavaScript for global variables and functions

I've been curious about hoisting. I understand that if a global function shares the same name as a global variable, the function will overwrite the variable's name. Is this correct? Here is an example code snippet. (function() { console.log ...

Utilize jQuery to target elements containing more than one class

Suppose an element has several classes as shown below: class="btn btn-primary add-movie-button is-on" Is it possible to select this element using only one class name with jQuery, for example: $(".add-movie-button") Can the method .hasClass("is-on") be ...