Discover the best method for sending multiple API requests to Vuex store using Nuxt middleware

I am having trouble figuring out how to make multiple API calls to Vuex store from Nuxt middleware. I have successfully implemented it for a single API call, but I can't seem to get it working for multiple APIs.

// middleware/log.js

import axios from 'axios';

export default function ({store}) {
    return axios.get(`http://my/api`)
        .then((response) => {
            console.log(response.data);
            store.commit('add', response.data);
        });
}

I attempted the following approach, but unfortunately, it didn't work as expected. Can someone please assist me with this?

import axios from 'axios';
async asyncData({store}) {
    return axios.all([
        axios.get('http://my/api'),
        axios.get('http://my/api2')
    ]).then(axios.spread((first, second) => {
        return {
            store.commit('add', first.data);
            store.commit('sub', second.data);
            // posts: first.data,
            // total: second.data
        }
    })).catch((err) => {
      error({ statusCode: 404, message: err.message })
    })

}

Answer №1

Removing the second return statement made everything work perfectly in my situation.

import axios from 'axios';
async asyncData( {store} ){
    return axios.all([
        axios.get('http://my/api'),
        axios.get('http://my/api2')
    ]).then(axios.spread((first, second) => {
            store.commit('add', first.data);
            store.commit('sub', second.data);
            // posts: first.data,
            // total: second.data
    })).catch((err) => {
      error({ statusCode: 404, message: err.message })
    })

}

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

Utilizing Ajax and Jquery to dynamically adjust CSS properties, dependent on data from a specific MySQL row

I've been working on a system to automatically update a Scene Selection page whenever a new number is added to the permission table in Mysql. The PHP for the login and retrieving the number from the members table is working fine. My issue now lies wi ...

Transform a flat 2D shape into a dynamic 3D projection using d3.js, then customize the height based on the specific value from ANG

Currently, I am utilizing d3.js version 6 to generate a 3D representation of the 2D chart shown below. Within this circle are numerous squares, each colored based on its assigned value. The intensity of the color increases with higher values. My goal is t ...

What is the best way to view or save the content of a PDF file using a web service?

As a newcomer to web services and JavaScript, I am facing a challenge with calling a web service that returns a PDF file in a specific format. Here is the link to view the PDF: https://i.stack.imgur.com/RlZM8.png To fetch the PDF, I am using the following ...

What is the best way to style a tooltip in an ASP.NET application using CSS?

protected void grd_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { foreach (TableCell cell in e.Row.Cells) { ...

Tips on toggling between slides with Bootstrap Carousel

I am in the process of designing a portfolio website and have encountered a challenge. I want to divide it into two sections - a brief introduction and a carousel for showcasing projects. While I have managed to set up both sections, I'm facing an iss ...

Vue - Dynamically rendering a string as an element

Is there a way to generate a vue component using a string stored in my database? For instance, the string includes a message with a smiling emoji. I store it like this: Some text with Emoji: :santa::skin-tone-3:, and then replace all valid strings between ...

Empty results received from MongoDB queries executed within an asynchronous loop

I'm encountering an issue where I have a list of IDs that I need to query Mongo with in a for loop, but it always returns an empty []. Initially, the queries were returning promises, so I switched from using forEach to a standard for loop as shown her ...

Create a visual representation of an image by sketching a detailed line profile using HTML5's

I am attempting to create an intensity profile for an image, using the x-axis as the line's length on the image and the y-axis as the intensity values along the length of the line. How can I achieve this on an HTML5 canvas? I have tried the code below ...

Converting the 'require' call to an import may be a more efficient method when importing package.json in a typescript file

In my current project, I am creating a class where I am directly accessing the package version number like this: const pkg = require('../package.json') export class MyClass() { constructor() { // Set the base version from package.jso ...

AngularJS: Utilizing ellipsis for text overflow and optimization

As a beginner in angularJS, I might have made some mistakes... Can anyone guide me on how to properly implement this plugin: https://github.com/BeSite/jQuery.dotdotdot on my table? Currently, the performance of my edit form and table is very slow. What c ...

Tips on programmatically filtering angular lists

Is there a way to programmatically filter an Angular list? I'm currently working on a project where I need to filter subcategories by clicking on categories. For example, when clicking on "Drinks," I want to display items like Coke, Fanta, Pepsi... ...

Is there a way to utilize JavaScript or jQuery to modify the background color of the `Save` and `Cancel` buttons within a SharePoint 2013 edit form?

Is there a way to modify the background color of the Save and Cancel buttons on a SharePoint 2013 edit form using JavaScript or jQuery? ...

Maximizing for-loop efficiency: the advantage of caching array length

Let's compare two variations of a loop iteration: for (var i = 0; i < nodes.length; i++) { ... } and var len = nodes.length; for (var i = 0; i < len; i++) { ... } Would the second version be faster than the first one in any way? ...

Passing Props in Vue-Router: A Guide

I've encountered an issue with passing props using Vue-Router. I'm struggling to access the props in the next view after routing. Here is my methods object: methods: { submitForm() { let self = this; axios({ method: &apo ...

Ways to update the initial value received as props in Vue3?

Imagine you're working with a todo-list component that displays the provided todos, where todos is of type Ref. <todo-list :todos="todos"/> This todo-list component also allows users to delete any of the displayed todos. However, in ...

Is there a way to dynamically alter the content depending on the index of the current slide using swiper.js?

Hi, I am new to utilizing the Swiper framework and so far, it has been one of the best sliders I have ever experienced. Currently, I am trying to establish a connection between 2 div tags - one tag holds the content of each slide while the other tag contro ...

When using Selenium WebDriver to locate an object, an error may occur stating that the result of the xpath expression is "[object Text]" instead of an element as expected

I am currently utilizing Selenium to validate the existence of specific text within a web page. Here is an example of how the HTML appears. <html> <div class="a-content"> <!--!-->==$0 " Text to Locate" <b ...

When do Angular.js memory leaks become a cause for concern?

My application is quite large, built on angular with nested states, directives, and data tables. We recently decided to switch to a full single-page setup, which raised some performance concerns. While Chrome seems unaffected visually, Firefox appears to s ...

Enhancing a component with injected props by including type definitions in a higher-order component

Implementing a "higher order component" without types can be achieved as shown below: const Themeable = (mapThemeToProps) => { return (WrappedComponent) => { const themedComponent = (props, { theme: appTheme }) => { return <Wrapped ...

Is there a way to confirm if I am taking a direct route instead of a detour?

My task seems simple enough: working with Vue3 and the Vue Router, I have a Home.vue component set at the route /, as well as a ProductDetails.vue component at the route /product. I am looking to trigger a specific action when a user navigates to my / rou ...