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

Assigning a session variable through a dropdown selection

Currently, I am working on a custom WordPress theme that involves setting a session variable based on the value selected from a dropdown box. This session variable is then used to determine which container should be loaded. The code snippet below shows whe ...

Putting retrieved data from firebase into an array using Angular and Firebase format

Hey everyone, I'm currently facing an issue with formatting my Firebase data into an array. Below is the service where I am retrieving data from Firebase: File name: subcategory.service.ts export class SubcategoryService { subcategoryRef: Angula ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

Injecting Javascript before page code in Chrome Extension Content Script allows for manipulation of webpage elements

I am currently working on developing a Chrome extension that involves injecting a script into a webpage before any other scripts present. This is crucial for my project as I am utilizing the xhook library to intercept XHR requests, which necessitates overw ...

Distributing your React component on npm

I've been working on a React component for over a week now and I'm struggling to publish it on NPM. The lack of credible resources online has made this process challenging for me. Can anyone offer step-by-step guidance or recommend reliable reso ...

Learning how to access my CSS file using Express and Node.js

I am new to using express and node.js. I am trying to develop my app, but for some reason, my style.css file is not being recognized and I am unsure why. Initially, I attempted to use .scss files, but after researching, I discovered that it was not possi ...

What is causing my controller action to create two new records instead of just one?

My current issue involves a simple Razor view featuring a button designed to add a new record to a table within my SQL database. The button is equipped with an Ajax function that triggers a call to the controller. I've experimented with two different ...

Utilize map() and concat() in JavaScript for more streamlined code - a tidier approach

Is there a way to optimize the code below by combining map() and concat() for efficiency? const firstColumnData = data.map((item: any) => { return item.firstColumn; }); const secondColumnData = data.map((item: any) => { return item.secondColumn; } ...

I'm confused why this code is functioning in JSFiddle but not on my HTML webpage

For the first time, I am encountering this issue. I am currently attempting to integrate this code into my application http://jsfiddle.net/TC6Gr/119/ My attempts include: Pasting all the jsfiddle code in a new page without my code, but it doesn't w ...

best way to retrieve state from redux-toolkit (excluding initial state) in a Next.js environment

I am attempting to access the state of redux-toolkit in Next.js's getStaticProps (After saving the accessToken in the store, I need to access the store from getstaticprops for the API it requires) Here's what I have tried: export default functi ...

TypeScript compilation error - No overload is compatible with this call

Currently, I am working on a project using TypeScript alongside NodeJS and Express. this.app.listen(port, (err: any) => { if (err) { console.log("err", err) } else { console.log(`Server is listing on port ${port}`); } }); The co ...

Issue with Vue canvas $ref not being defined on resize causing error, but oddly still seems to function correctly

Within my application, there exists a tabbed interface. One of the tabs contains a canvas element that dynamically adjusts its size to fit the window whenever it is resized. The functionality works seamlessly at first, but upon switching tabs and returning ...

The JScolor Color Picker has a slight misalignment

I am having an issue with the jscolor color picker on my webpage. The rainbow part of it appears offset within the rest of the picker. You can see what it looks like on my site here: (https://ibb.co/9N8dHXs). On my website, I have a large canvas for three ...

Running a local project with the help of the Express framework

// Setting up the configuration for serving files from the source directory var express = require('express'); // Importing express module var path = require('path'); // Importing path module var open = require('open'); // Imp ...

Toggle the Bootstrap navbar class based on the current scroll position

I'm currently working on the development of a website that includes a feature where a static navbar transforms into a fixed navbar after scrolling down 500px. The transition from "navbar-static-top" to "navbar-fixed-top" is functioning properly. Howev ...

Conceal element when unchecked

There is a checkbox pre-selected labeled "Use profile address" with the address displayed below. If the customer unchecks the checkbox, the address that was shown before will disappear and a new input field for adding a different address will appear. I a ...

The console is throwing an error because the store variable in the template is only filled after making an asynchronous API call

Within my component, I am showcasing various properties (exemplifying two below) of the selectedPlan store variable after receiving its value from the store: <div> {{ selectedPlan.periodTitle }} </div> <div> {{ selectedPlan.currency } ...

Adjust the dimensions of the dropdown menu

Objective: How can I adjust the width of a select dropdownlist that is utilizing bootstrap v2? Challenge: I am uncertain about how to modify the width in the context of bootstrap. Additional Information: Keep in mind that there are three dropdownli ...

Issue encountered when trying to insert an array in JavaScript into MongoDB using Mongoose

I am currently learning about node.js and mongodb. I attempted to insert a JavaScript array variable into mongodb using mongoose, but encountered an error. Upon running this code, I received the following error message: ValidationError: CastError: Cast t ...

Searching for specific values within data attributes using jQuery wildcards

I am currently utilizing the data_attribute on this page and have the following elements with data attributes. No. 1.<div class="row hidden" data-party-registration-source-type-id="1"> 2.<div class="row hidden" data-party-registration-source- ...