Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

javascript - Array is not array anymore when passed into Vuex action function

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

I'm not quite understanding what's going on with my code. I'm trying to pass an array into an action function inside of my Vuex store. If I return a Promise inside of that action function, then the parameter being passed isn't of type Array and is instead an Object, which results in the reject() error that I have for the Promise.

Here's some code for context:

filterEvents({ commit }, events) {
    console.log(Array.isArray(events)); //this ends up 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's 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 ends up true
        console.log(res.data.events.event);

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

Here's the output from the Chrome developer console. First two outputs are from getEvents and last two are from filterEvents

Chrome Developer Console

Would really like an explanation as to why this is the case. I'm going to bet it's something small, but it's 3 a.m. at the moment and my brain can't wrap around why it's not of type Array when passed into filterEvents.

question from:https://stackoverflow.com/questions/65881182/array-is-not-array-anymore-when-passed-into-vuex-action-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I always try to check the length prop of the array which helps me out in such cases.

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

        .....
    });
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...