Troubleshooting the "filter is not a function" error in a VueJs Vuex getter

As a newcomer to frontend development and Vue js, I am looking to integrate state management into my application. While setting the state with the response from my API works fine, I encountered an issue when trying to filter the results in a getter using the filter function (getActiveLeagues). The error message 'filter is not a function' suggests that the result is not being treated as an array, even though I have declared my state as an array:

const state = {
  leagues: [],
};

const getters = {
  getAllLeagues: (state) => state.leagues,
  getActiveLeagues: (state) => state.leagues.filter((league) => league.archivated === false),
};

const actions = {

  async getAllLeagues({ commit }) {
    const response = await axios.get(`${server.baseURL}/api/league`);
    console.log(response);
    commit('setLeagues', response);
  },
};

const mutations = {
  setLeagues(state, leagues) {
    state.leagues = leagues;
  },
};
export default {
  state,
  getters,
  actions,
  mutations,
};

I receive an array from the API:

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

This is how my Vuex.Store call looks like:

import Vue from 'vue';
import Vuex from 'vuex';
import posts from './modules/postModule';
import leagues from './modules/leagueModule';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    posts,
    leagues,
  },
});

The result of the state watch: https://i.sstatic.net/TOzlG.png https://i.sstatic.net/CShtv.png It may just be a simple mistake on my end since I am new to this, but I appreciate any help. Thank you.

Answer №1

Personally, I haven't had the chance to dive into using modules and how they compare to flat state. To gain a better understanding, consider adding a console.log(state) inside the getter.

One key observation I made, which differs from the documentation, is that state should be declared as a function in the module. For example:

const state = () => ({
  leagues: [],
});

For more information, you can refer to: https://vuex.vuejs.org/guide/modules.html

UPDATE (in response to your latest screenshot)

It seems like state.leagues.leagues might be what you're after (possibly due to module namespacing), however, even that isn't an array but an object with a nested data property that holds an array.

To start addressing this, consider the following:

commit('setLeagues', response.data);

Assuming your module state should already be receiving its namespaced substate, there might not be a need for further modifications. Nevertheless, if issues persist, you could also try the following suggestion out of curiosity:

getActiveLeagues: (state) => state.leagues.leagues.filter((league) => league.archivated === false),

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

How to export HTML table information to Excel using JQuery and display a Save As dialog box

This script has been an absolute lifesaver for my web application. Huge thanks to sampopes for providing the solution on this specific thread. function exportToExcel() { var tab_text="<table border='2px'><tr bgcolor='#87AFC6& ...

Delete any fields that start with the name "XX"

Here is an example document extracted from a collection: { "teamAlpha": { }, "teamBeta": { }, "leader_name": "leader" } My goal is to remove all fields that begin with "team" from this document. Therefore, the expected outcome would be: {leader_name: "l ...

Using Node's Express bodyParser() to access a JSON string that has been parsed

Question: How can I retrieve the parsed JSON object from the server side? I have successfully sent a JSON string to the server, but I am having trouble accessing the object once it is parsed. The client-side script for sending the JSON data is as follows ...

I'm having trouble getting the Bootstrap 5 Carousel to work, even though I directly copied the code from the official website

Currently, I am designing a webpage utilizing Bootstrap 5 and incorporating the CDN for functionality. Although, when attempting to implement their carousel feature, it does not seem to be functioning as expected. The only modification I have made to their ...

Exploring the JSON object and dynamically incorporating elements into it is my goal as I navigate through AngularJS

I'm seeking a way to display the entire JSON data in a tabular format, with the ability to dynamically loop through any additional values that are added. Here is an example of my current JSON: $scope.tableContent = [ { id: 1, ...

The variable 'document.prodimage' does not exist or is not a valid object

Encountering a JavaScript error in IE8 on Windows 7 when loading the page: document.prodimage is null or not an object. I have excluded my custom dynamic code responsible for API calls to fetch data, which populates elements such as images & links based o ...

Exploring the Record type in Typescript when using React's useContext

I'm currently facing challenges in grasping the concept of record types within a generator function that I am developing for React contexts. Below is the code snippet of my generator function: import * as React from 'react' export type Sta ...

Using props in Vue with CSS modules: A comprehensive guide

row.vue <script> export default { name: "Row", data() { return { app: [ "row", "row-test", "flex-center" ] } }, template: ` <div :class="$module[app]"><slot&g ...

Retrieve the XML file from the webpage and save it to a specific directory using Java and the Selenium framework with the Chrome browser

Retrieve xml file from the website and save it to a specific location using java or selenium with Chrome browser. Here is the snippet of HTML code: <!-- Start of Code which handles XML Download--> <a href="javascript:downloadXML()"> <img s ...

Step-by-step guide to incorporating an external script into a React application

I am facing a common issue regarding loading external scripts in my React application. Despite researching numerous articles and similar questions on StackOverflow, I have not been able to resolve it. My current challenge involves integrating Yodlee Fastl ...

Tips for creating a horizontal list within a collapsible card

When a user clicks on a button, I am dynamically populating a list of items. Despite using list-group-horizontal, I am unable to make it display horizontally. HTML code <div id="textarea_display" class="mt-2 "> <label&g ...

Encountering a JS error that states: "Uncaught SyntaxError: missing ) after argument list" when running the following code

I keep encountering the error message: "Uncaught SyntaxError: missing ) after argument list" when I try to call the delete function within the createHtmlview function. console.log("Delete Item is being called") } ...

Tips for adjusting font-family on Vuetify components:

I am looking to change the default Vuetify font family from Roboto, but I only want to do this for a specific element rather than globally. Most solutions I have come across address changing the font family globally, which is not what I need. Can anyone ...

Which is more powerful: Angular's change detection or directly editing HTML?

One thing I've heard is that Angular's change detection can potentially cause lag in an application when receiving a large amount of data from a websocket. In my setup, the data comes from the socket, updates a variable in the component, and then ...

jQuery not functioning properly on mobile browsers

I'm currently working on an image uploader using jQuery and AJAX. It's functioning properly in computer browsers but encountering issues on mobile browsers. I did have it working once, but after making some changes, it stopped functioning correct ...

Design a CreateJS/EaselJS website, comprised of multiple web pages, that is not focused on gaming

I have developed an existing HTML5 Canvas webpage composed of multiple pages, buttons, and hotspots using pure canvas javascript code. The reason I refer to 'buttons' and 'hotspots' in quotes is because I created them from scratch in j ...

Take action once the Promise outside of the then block has been successfully completed

Presented below is the code snippet: function getPromise():Promise<any> { let p = new Promise<any>((resolve, reject) => { //some logical resolve(data); }); p.finally(()=>{ //I want do something when ou ...

Why isn't my jquery AJAX load displaying correctly?

Despite searching for answers to my question, I haven't found a solution that works for me. I am currently experimenting with bootstrap, jquery, ajax, mqtt, and other technologies using a bootstrap template. I encountered an issue with ajax load and I ...

Struggling to locate module 'react' is causing the unresolved error to persist

I'm really puzzled by the persisting error message that keeps popping up Uncaught Error: Cannot find module 'react' despite exhausting all possible solutions listed in the threads below: Uncaught Error: Cannot find module "react&quo ...

Nodemon is failing to automatically re-run the changes I've made in my local codebase

Recently, I developed a basic node function that simply outputs "hello world." When I ran the script using the command line node myfirst.js, it successfully displayed the message in the browser. Then, I decided to install nodemon so that it would re-exec ...