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

Navigating with Vue Router in a Nuxt JS vuex Store

In my app, I'm currently developing a login/register system using Firebase and Vuex for authentication and database management. Within Nuxt JS, I have implemented actions to create a user, log them in, and sign them out. After a successful registrati ...

The .keypress() function isn't behaving as expected

I've encountered a coding dilemma. Below is the code in question: $(document).ready(function () { var selectedDay = '#selected_day'; $(function () { $("#date").datepicker({ dateFormat: "DD, d M yy", a ...

Connect this - initiate the removal of an item

I am seeking assistance from more experienced colleagues to help me understand the code below and implement it in my App. The main objective is to trigger a REDUX action from a button, which will delete an item from a database. Here is the code that curr ...

Develop interactive, reusable custom modals using React.js

I am currently working on creating a reusable modal: Here is my component setup: class OverleyModal extends Component { constructor(props) { super(props); } openModal = () => { document.getElementById("myOverlay").style.display = "blo ...

Having trouble with importing a TypeScript class: encountering a "cannot resolve" error message

Could you lend me your expertise? I'm puzzled by this issue that seems to be quite simple and straightforward: export class Rectangle { height: number = 0 width: number = 0 constructor(height: number, width: number) { this. ...

Accessing store in Vue, the getter function returns a value representing whether the user is currently logged

I have the user state stored in my Vue store, but when I try to access it like this: let isLoggedIn = store.getters.isLoggedIn Instead of getting a simple true or false, I see this in the console: ƒ isLoggedIn (state) { return state.user ? true : false ...

Implement Material UI TextField to ensure all required fields are properly formatted

Looking to customize the underline border color of TextFields marked as mandatory within a form using react-hooks-form. I understand that I need to define a style for these fields, but I'm struggling with where to start... This is the current code s ...

Exploring the use of callbacks in React closures

After diving into a React related article, I delved deeper into discussions about closures and callbacks, checking out explanations on these topics from Stack Overflow threads like here, here, and here. The React article presented an example involving thr ...

Streaming HTTP content on a domain secured with HTTPS using HTML5

Is it possible to stream HTTP on an HTTPS domain without triggering browser security errors? By default, the browser tends to block such requests. I rely on the hls.js library for desktop support with .m3u8 files. When I play content directly (on mobile o ...

Issue with Type-Error when accessing theme using StyledComponents and TypeScript in Material-UI(React)

I attempted to access the theme within one of my styled components like this: const ToolbarPlaceholder = styled('div')((theme: any) => ({ minHeight: theme.mixins.toolbar.minHeight, })); This information was found in the documentation: htt ...

How to dynamically increase vote tallies with React.js

The voting system code below is functioning well, displaying results upon page load. However, I am facing an issue where each user's vote needs to be updated whenever the Get Vote Count button is clicked. In the backend, there is a PHP code snippet ...

confirmation message upon completing a form submission

<script> var remainingCredit = document.getElementById("cor_credit"); var remaining = document.getElementById("remain_credit"); function validateForm() { if (remaining.value < remainingCredit.value) { return conf ...

Can someone please explain how to prevent Prettier from automatically inserting a new line at the end of my JavaScript file in VS Code?

After installing Prettier and configuring it to format on save, I encountered an issue while running Firebase deploy: 172:6 error Newline not allowed at end of file eol-last I noticed that Prettier is adding a new line at the end when formatting ...

In the Kendo AngularJS tree view, prevent the default behavior of allowing parent nodes to be checked

Hi there, I am currently using Kendo treeview with Angularjs. My tree view has checkboxes in a hierarchy as shown below Parent1 Child1 Child2 I would like the functionality to work as follows: Scenario 1: if a user selects Parent1 -> Child1, Child2 ...

Perform an action when the timer reaches zero

I am working with a database entry that contains the following information: { _id:"fdjshbjds564564sfsdf", shipmentCreationTime:"12:17 AM" shipmentExpiryTime:"12:32 AM" } My goal is to create a timer in the front end ...

Angular utilizing external parameter for Ajax requests

As a newcomer to Angular, I am eager to upgrade some old jQuery code with AngularJS. The task at hand is to extract a string from a span element, split it into two separate strings, and then use these as parameters in a GET request. I am dedicated to lea ...

AngularJS: The dynamic setting for the stylesheet link tag initiates the request prematurely

I'm encountering a problem that is somewhat similar (although not exactly the same, so please be patient) to the one discussed in Conditionally-rendering css in html head I am dynamically loading a stylesheet using a scope variable defined at the sta ...

Rearranging components in React does not automatically prompt a re-render of the page

I'm currently working on a project to display the update status of my Heroku apps. The issue I encountered was that the parent component (Herokus) was determining the order, but I wanted them sorted based on their update dates starting from the most r ...

If the FedEx function does not receive a payment, it will need to return a value of Payment Required

I am struggling with understanding functions, parameters, and arguments in JavaScript as I am new to it. My goal is to have a function that returns different values based on the payment amount. If no payment is passed, it should return "Payment Required", ...

Tips for smoothly animating and showing content as the user scrolls to a specific element on the page

Here is a sample template: <template> <div id="Test"> <transition name="fade"> <div class="row" id="RowOne"> <p>Lorem ipsum dolor odit qui sit?</p> </div> ...