Can Nuxt's asyncData handle multiple requests with conditional statements?

I've been grappling with this issue for some time now. I understand how Nuxt asyncData can be used to make either one request or multiple requests, but is there a way to incorporate conditional logic for making multiple requests based on a query parameter? For instance, sometimes it should make one request and other times two requests, depending on the query param.

async asyncData({ $axios, route }) {
  if (route.query.query) {
    if (route.query.tab === 'companies') {
      // API Call "Search companies"
      return await $axios.$get(`/v1/search/companies/${route.query.query}`).then((res) => {
        return {
          tab: 'companies',
          query: route.query.query,
          companyResults: res.data.data,
        }
      })
    } else {
      let company = null

      if (route.query.company) {
        // API Call "Read a company"
        await $axios.$get(`/v1/companies/${route.query.company}`).then((res) => {
          company = res.data
        })
      }

      // API Call "Search requests"
      return await $axios.$get(`/v1/search/requests/${route.query.query}`).then((res) => {
        return {
          company,
          tab: 'requests',
          query: route.query.query,
          requestResults: res.data.data,
        }
      })
    }
  }
}

The issue lies within the else statement. When the "company" query param is set, I want it to trigger both the "Read a company" and "Search requests" API calls. However, if the query parameters are not set, then only the "Search requests" API call should be made.

Although all the correct API calls are being made when I run this code, the data is not being returned correctly from asyncData.

Answer №1

It seems like the issue may be due to a combination of async/await and promises in your code. Consider trying the following approach:

async fetchData({ $axios, route }) {
  if (route.query.query) {
    if (route.query.tab === 'companies') {
      // Making API Call "Search companies"
      const response = await $axios.$get(`/v1/search/companies/${route.query.query}`)
      return {
        tab: 'companies',
        query: route.query.query,
        companyResults: response.data.data,
      }
        
    } else {
      let company = null
      if (route.query.company) {
        // Making API Call "Read a company"
        const response = await $axios.$get(`/v1/companies/${route.query.company}`)
        company = response.data
      }

      // Making API Call "Search requests"
      const reponse = await $axios.$get(`/v1/search/requests/${route.query.query}`)
      return {
        company,
        tab: 'requests',
        query: route.query.query,
        requestResults: reponse.data.data,
      }
    }
  }
}

Answer №2

It turns out that the issue was not related to the asyncData function after all. Interestingly, when using $get in Nuxt Axios, there is a convenient shortcut that automatically returns the data instead of an object with a data property. This meant that I simply needed to update the code from accessing ".data.data" to just ".data".

async asyncData({ $axios, route }) {
  if (route.query.query) {
    if (route.query.tab === 'companies') {
      // Making API Call for "Search companies"
      const response = await $axios.$get(`/v1/search/companies/${route.query.query}`)

      return {
        tab: 'companies',
        query: route.query.query,
        companyResults: response.data,
      }
    } else if (route.query.company) {
      // Making API Calls for "Read a company" and "Search requests"
      const [companyResponse, requestsResponse] = await Promise.all([$axios.$get(`/v1/companies/${route.query.company}`), $axios.$get(`/v1/search/requests/${route.query.query}`)])

      return {
        company: companyResponse,
        tab: 'requests',
        query: route.query.query,
        requestResults: requestsResponse.data,
      }
    } else {
      // Making API Call for "Search requests"
      const response = await $axios.$get(`/v1/search/requests/${route.query.query}`)

      return {
        tab: 'requests',
        query: route.query.query,
        requestResults: response.data,
      }
    }
  }
},

I want to give a special shoutout to Daniel Roe for his help on the Nuxt Github Repo.

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

The functionality of making Slim POST requests is currently not functioning as expected within the Ionic

An issue is arising with my app that makes calls to a REST API using POST and GET methods. The app I'm developing with Ionic works perfectly when emulated using the command: ionic serve --lab However, when running the app on an actual device, calls ...

Creating a Mongoose schema to store an array of objects, where updates will automatically add new objects

const mongoose = require('mongoose'); module.exports = mongoose.model('GridModel', { Request_Id : { type : Number, required : true }, viewStudents : { type : Array , default : [] } }); The mongoose model above needs to b ...

How to remove every instance of an item in an array based on its unique identifier using JavaScript

Is there a way to clean up an array of objects by removing duplicates with the same id? In this case, I only want to keep the object with id 1. This is my approach: let data = [{ "selected": true, "id": 3, "ProductName": "Aniseed Syrup", ...

"Learn how to seamlessly submit a form and display the results without the need to refresh the

Here is the form and result div: <form action="result.php"> <input type="checkbox" name="number[]" value="11" /> <input type="checkbox" name="number[]" value="12" /> <input type="checkbox" name="number[]" value="13" /> <input t ...

What is the best way to incorporate a progress bar animation into my notification?

Seeking assistance to implement an animated progress bar that changes colors gradually over time based on a variable [timer]. Can anyone lend a hand with this? Thank you! https://i.sstatic.net/lhgeF.png $(document).ready(function(){ window.addEvent ...

Jasmine examination fails to progress to the subsequent segment of the promise

I want to test a specific function: function initializeView() { var deferred = $q.defer(); if(this.momentArray) { core.listMoments(constants.BEST_MOMENT_PREFIX, '').then(function(moments) { //Ommit ...

Dynamically obtaining the screen width in JSP using a variable

Could someone provide assistance on how to resize an image using an img src="blah.jpg?width=x" so that my page can be displayed at various sizes? I just need x (width) as a JSP variable. Update 2021: It's been 9 years since this question wa ...

Resizing an image with six corners using the canvas technique

Currently, I am facing two issues: The topcenter, bottomcenter, left and right anchors are not clickable. I'm struggling with the logic to adjust the image size proportionally as described below: The corner anchors should resize both height and wi ...

Controller fails to initialize when utilizing $location.path or $state.go

Issue with Controller Initialization after Redirect in Ionic App I have encountered an issue where the controller is not initializing on the same page when I use $state.go or $location.href. In my Ionic app, I am using a sidemenu to pass category Id to th ...

transforming a text input into unadorned plain text

Currently, I am in the process of creating a small HTML form that consists of a single textbox input. Once the user enters text into this textbox and clicks on a button located at the end of the page, I would like the textbox to transform into normal plain ...

Encountering a problem with npm installation during the setup of node-sass

While attempting to run the npm install command, I encountered an error during the installation of node-sass. https://i.stack.imgur.com/qcDaA.png https://i.stack.imgur.com/YxDi2.png Here is my package.json file: { "name": "XXXXX", ...

Firing ng-change with fileModel or input type="file"

Is there a way to trigger ng-change when a change occurs with this file directive? I have implemented a custom file directive for this purpose. The Directive: app.directive('ngFileModel', ['$parse', function($parse) { return { ...

JQuery Form Wizard - Adding a Finish Button Linked to a Page

Having some difficulty linking the finish button on my Jquery Form Wizard within my Flask App to a link. I attempted to test the functionality by creating a simple alert, but that didn't work either. I'm certain that I missed a step somewhere, b ...

Develop a time-sensitive store system using HTML and JavaScript that toggles between open and closed status based on set

I am looking to develop a time-based Open/Closed store using HTML and JavaScript. The concept is that on Fridays, the element with id="friday" should be displayed, otherwise, show the element with id="week". Additionally, if the time i ...

Can a FilePicker be Cleared Automatically through Code?

Currently, I am implementing an‘<input type="file" . . .’ to select files individually and then attach them to a table located right under the file picker. This functionality is quite similar to using the attachment button on a SharePoint form’s r ...

Firebase functions are giving me a headache with this error message: "TypeError: elements.get is not

Encountering the following error log while executing a firebase function to fetch documents and values from the recentPosts array field. Error: Unknown error status: Error: Unknown error status: TypeError: elements.get is not a function at new HttpsEr ...

Error encountered when attempting to use the .save() method on a [mongoose_model_object] - the function contact.save is

In this scenario, the middleware 'auth' is responsible for generating a JWT and authorizing the user. I have also created a Mongoose model called Contact. However, when attempting to execute contact.save(), I encounter an exception stating that c ...

Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model. This comparison needs to happen in th ...

Add a span tag with the class "javascript" around the index of a character within a string

Within an element, I have a string as such: <p>I like trains and planes</p> Using jQuery's .text(), I extract the text and store it in a variable. var str = $('p').text(); I aim to identify a specific character, let's sa ...

Unable to confirm form validation with Vue

Recently, I started working with Vue and encountered a problem while running the code below. The error message "ReferenceError: $vAddress is not defined" keeps popping up. Despite my efforts to search for solutions online, I couldn't find any that add ...