When an array is passed into a Vuex action function, it transforms into something other than just

EDIT: Added extra code in the filterEvents snippet for more context.

I'm struggling to understand the behavior of my code. My goal is to pass an array into an action function within my Vuex store. However, when I return a Promise inside that action function, the parameter passed is not recognized as an Array but as an Object instead. This leads to the rejection error in the Promise.

Here is some code for reference:


filterEvents({ commit }, events) {
    console.log(Array.isArray(events)); //this returns false
    console.log(events);

    return new Promise((resolve, reject) => {
        if (!Array.isArray(events)) {
            reject("Invalid argument: is not of type Array.");
        }

        let filtered = events.filter((event) => {
            let now = new Date();
            let event_stop = new Date(event.stop_time);

            if (event_stop >= now || event_stop == null) {
                return event;
            }
        });

        resolve(filtered);
    });
}

Here is where I call filterEvents; inside of getEvents;


getEvents({ state, commit, dispatch }, searchParams) {
    .....
    
    eventful.getEvents(searchParams).then(async (res) => {
        .....

        console.log(Array.isArray(res.data.events.event)); //this returns true
        console.log(res.data.events.event);

        /* where I call it */
        await dispatch("filterEvents", res.data.events.event).then((res) => {
            .....
        });
    }).catch((err) => {
        .....
    });
}

The Chrome developer console output shows the results. The first two outputs are from getEvents and the last two are from filterEvents

https://i.sstatic.net/UKZ35.png

I really need an explanation for this issue. It must be something minor, but at 3 a.m. my brain is struggling to understand why filterEvents is not recognizing the input as an Array.

Answer №1

One method I often utilize is examining the length property of the array, as it proves to be quite beneficial in scenarios like these.

...
return new Promise((resolve, reject) => {
        if (!Array.isArray(events) && !events.length) {
            reject("Invalid argument: is not of type Array.");
        }

        .....
    });
...

Answer №2

Upon closer inspection of the object logged in the console, I finally grasped the issue at hand. It turns out, Vuex actions require two arguments when passing in a payload to the function. Initially, I had defined the action like this:

filterEvents(events) {
    .....
}

However, what I actually needed to do was:

filterEvents(context, events) {
    .....
}

The context argument provides access to functions like commit and dispatch. Typically, I destructure the context object as { commit, dispatch }, which led me to overlook the necessity for the context argument. In reality, you can still use commit and dispatch without destructuring the context object, like so:

context.commit('function', payload);

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

Troubleshooting Full Screen Problems with Three.js

Despite my efforts to troubleshoot, I am still encountering a frustrating issue with the Three.js API. Even after thoroughly studying the API documentation, browsing through StackOverflow questions, and using debugging tools like firebug and chrome's ...

Webpack is failing to recognize certain CSS files

My development stack includes Vue.js 2.5.15, Webpack 4.12.0, css-loader 0.28.11, ASP.Net Core 2.1 in Visual Studio 2017. Starting with the Visual Studio asp.net core template project for Vue and Typescript, I prefer to have individual small CSS files with ...

The invocation of `prisma.profile.findUnique()` is invalid due to inconsistent column data. An invalid character 'u' was found at index 0, resulting in a malformed ObjectID

The project I'm working on is built using Next.js with Prisma and MongoDB integration. Below is the content of my Prisma schema file: generator client { provider = "prisma-client-js" } datasource db { provider = "mongodb" url = env("DATABA ...

Tips for displaying real-time data and potentially selecting alternative options from the dropdown menu

Is there a way to display the currently selected option from a dropdown list, and then have the rest of the options appear when the list is expanded? Currently, my dropdown list only shows the available elements that I can choose from. HTML: < ...

The expo-location feature is failing to accurately record and store all of the positions within the array

Incorporating expo-location in my react-native app, I utilize it to track the user's positions and store them in a redux object. While debugging the object reveals that all positions have been successfully inserted, upon retrieving this array, it turn ...

Hiding content in HTML with the Display:none property

After exploring various posts on this topic, I am still unable to find a solution that fits my specific scenario. Despite the challenges, I thought it would be worth asking for recommendations. Currently, I have a PowerShell script generating a report in ...

What is causing the colorful background to not fully cover my page when I make the window smaller?

I'm currently designing a webpage that features a dynamic gradient background. Within this webpage are two columns - one displaying an image of a phone, and the other containing text. In full screen mode, everything looks perfect. The gradient stretch ...

Exploring the wonders of retrieving JSON data in PHP through an Ajax request

A front-end developer is sending an array of data formatted as a JSON object using an Ajax call. The JSON object structure is shown below: { "name": " Test Name ", "image_url": "test URL", "include": [ "1" ], "dimension": [ null ], "media_type" ...

What is the best way to include multiple hostnames and pathnames in a Next.js configuration file for image assets?

My attempt to import multiple images from different hostnames for next/image is not working as expected. In my next.config.js, I have tried the following setup: module.exports = { images: { remotePatterns: [ { protocol: 'https&apos ...

Give properties to a function that is being spread inside an object

While working with React, I am facing a challenge of passing props from the instanced component into the mockFn function. The code example below is extracted and incorporates Material UI, but I am struggling on how to structure it in order to have access t ...

Clicking the ASP button does not trigger the onclick event when a web user control is included on the webpage

I have been working on a web form application that I developed using the visual studio template. The template includes a content placeholder that gets replaced by the content of each accessed page. One particular page, which contains server controls like t ...

NodeJS process that combines both client and server functionality

Attempting to develop a test echo server with both client and server in the same node process. When the code is split into two files (server and client), it functions correctly, but when combined into one file, it fails. How can I make it work within a sin ...

Transform the HTML content into a JSON format file

I'm currently developing an online marketplace and trying to convert all product information like name, price, and description into json format. I have a sample code featuring a selection of products displayed in rows. <div class='cakes'& ...

Should we retain the express variable for a specific purpose?

Being a developer who is still learning the ropes, I fail to understand the necessity of creating or retaining the express variable in an express/Node app. Instead of following this conventional approach: const express = require('express'); con ...

Debugging Typescript code with line numbers

When opening the console in a browser, typically the javascript line number of a function call or error message is displayed. However, my current setup involves using TypeScript, which gets compiled to Javascript. I am wondering if there is a way to retr ...

JavaScript: Techniques for extracting multiple digits from a text

Enter: "WASHINGTON (Reuters) U.S. stock index futures indicated a marginal recovery on Wall Street on Thursday, as futures for the S&P 500 rose by 0.34 percent, Dow Jones futures gained 0.12 percent, and Nasdaq 100 futures increased by 0.51 percent ...

Tips for maintaining a scrollable Material-UI Table with dynamic height?

I'm encountering an issue with the Material-UI Table component in terms of its size and scrollability. Summary: The Material-UI table only becomes scrollable when its parent has a fixed size. If I set the size to 100% to fit the parent, it overflows. ...

"Present a continuous sequence of images in HTML to create a dynamic video-like experience

A PHP file has been created to extract images from a MySQL database and display them as a sequence of images that update every half second. Using the setInterval method in JavaScript, the page is refreshed every half second to display a new picture. $(doc ...

Trouble with Add To Cart feature in React app due to issues with Context API

I have been following a tutorial located here. I followed the steps exactly and even checked the code on the related github repository, which matches. However, when I try to add a product to the cart by clicking the button, the state does not update. In Re ...

What is the best way to achieve varying margins when adding divs in CSS?

Encountering CSS margin issues when adding new divs. Desiring a large margin between the Create Div button and minimal margin between Example Text Here. The desired outcome Margin is too small between Create Div button and Example Text Here, but good bet ...