unable to retrieve getters within the store module

This is the explanation of my store module.

// rest defined earlier
const _GETTERS = {
  getName: state => {
    return state.current.name;
  },
  getLastName: state => {
    return state.current.lastName;
  },
  getFullName: (state, getters) => {
    // return `${state.current.name} ${state.current.lastName}`;
    return `${getters.getName()} ${getters.getLastName()}`;
  },
  getMailAddress: state => {
    return state.current.mailAddress;
  }
};

const UsersStore = {
  ...
  getters: _GETTERS
};

The above code snippet represents my user-store module. I encountered an error stating

Uncaught TypeError: getters.getName is not a function
. However, changing the code to access the state instead of the getters resolved the issue. Below is the main store object where I include the module.

export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  state: _state,
  getters: _getters,
  actions: _actions,
  mutations: _mutations,
  modules: {
    users: UserStore
  }
});

Rendering this section works perfectly fine when directly accessing the store without utilizing getters.

import {Component, Vue} from 'vue-property-decorator';
import {mapGetters} from 'vuex';

const template = require('./app-footer.vue').default;

@Component({
  mixins: [template],
  computed: {
    ...mapGetters({
      name: 'getFullName'
    })
  }
})
export default class AppFooter extends Vue {
}

Answer №1

Issue

This is where you ran into trouble:

Uncaught TypeError: getters.getName is not a function

This is the snippet of code causing the error:

getFullName: (state, getters) => {
  return `${getters.getName()} ${getters.getLastName()}`;
},

The error occurs because you are mistakenly trying to invoke getters.getName as a function (getters.getName()) when it is not actually a function.

Contrast this with the following correct usage that avoids an error:

getFullName: (state, getters) => {
  return `${state.current.name} ${state.current.lastName}`;
},

In this case, state.current.name is accessed as a property and not called as a function.

For more guidance on using getters in Vuex, refer to the getter documentation.

Resolution

To resolve the issue, eliminate the unnecessary parentheses when calling getters.getName.

Remarks

Why isn't getters.getName a function? It seems like you defined it as one. Take a look at this example from the docs – doneTodos is definitely a function, right?

getters: {
  doneTodos: state => {
    return state.todos.filter(todo => todo.done)
  }
}

https://vuex.vuejs.org/en/getters.html

The methods you define on the getters object become getters on the store object. Getters enable access to dynamically computed values as if they were properties (i.e., without a function call).

Sometimes it's useful to allow access to a property that calculates a dynamic value, or you may want to show the status of an internal variable without requiring explicit method calls. In JavaScript, this can be achieved using a getter. While it's not possible for a property to have both a getter and a value, you can use a getter along with a setter to create a pseudo-property.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

Check out the MDN doc for details on how getters work.

VueJS takes your methods declared on the getters object and employs Object.defineProperty to set getters on the store object, thereby allowing you to retrieve dynamically computed properties. If you're familiar with VueJS's computed properties, the concept and usage are quite similar.

Additional Resources

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

Discover the most effective method for identifying duplicate items within an array

I'm currently working with angular4 and facing a challenge of displaying a list containing only unique values. Whenever I access an API, it returns an array from which I have to filter out repeated data. The API will be accessed periodically, and the ...

Laravel: Input information into a form containing multiple dropdown menus

I am in search of a Laravel or HTML example that demonstrates filling out a form with multiple drop-down lists. Here's my scenario: I have the following text inputs: name_customer, phone_customer, email_customer. I want the form fields to automatical ...

Implement techniques on items within a v-for loop in Vue 3 JavaScript

I am struggling with a simple task in Vue 3 - accessing the values of an item in a v-for array. <template> <div> <table class="table-auto w-full max-w-screen mt-4"> <thead> <tr> <th&g ...

Leveraging scanner-js within an Angular2 environment

Exploring ways to incorporate Scanner-JS into my Angular2 project, a tool I discovered while tinkering with the framework. Being a novice in Angular2, this question might be elementary for some. I successfully installed scanner-js via npm npm install sc ...

Troubleshooting Issue: Minified CSS in Vue.js not displaying correctly when deployed on Azure static website

I have successfully deployed a static vue.js website to Azure at The development build looks great in Chrome and Safari on OS X, and the production build works fine when served from the dist directory. However, the CSS doesn't seem to be rendering c ...

What is the best way to uninstall the Google Translation Plugin when transitioning to a new Vue component?

I'm facing a minor issue as I develop a website builder. It consists of two main parts: the builder and the preview section. Within the preview, I've included the Google Translation plugin: onMounted(() => { new google.translate.TranslateEle ...

What is the best way to refresh the script located within the head tag of an index.html file in an Angular

I've been looking for solutions, but I can't seem to find one. In my index.html file, I've placed some script within the head tag (even above the </body> tag) and included a $(document).ready function. The issue I'm facing is th ...

Creating a dynamic component in code with Vue.js is easy and efficient

I am currently in the process of developing a web application that utilizes HERE Maps to showcase event elements on a map. The application is being built using Vue.js. Among the various components being used, the HereMaps.vue component plays a crucial rol ...

Validation of parameter data types in Typescript

I need help differentiating between React.MouseEvent and React.KeyboardEvent in my TypeScript component foo(e: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>) { if(e is mouse event) { //do something } else ...

Angular is not programmed to automatically reflect updates made to my string array

let signalRServerEndPoint = 'https://localhost:44338'; this.connection = $.hubConnection(signalRServerEndPoint); this.proxy = this.connection.createHubProxy('MessagesHub'); this.proxy.on("ReceiveMessage", (message) => { ...

Displayable components within choices in a dropdown menu

Is it possible to dynamically update select options based on the visibility of elements in the DOM that are controlled by v-if? The current code I have does not seem to be updating the options as elements are hidden. <select class="form-control-sm fl ...

Sharing an array between two sibling components

Within my 'Home' component, users have the ability to create QR codes. I have implemented a method that generates an array of these QR items. Now, the challenge lies in passing this array to another component that is a sibling and not located wit ...

Utilizing Typescript for creating a function to serialize promises

I am in the process of developing a wrapper for promise-returning functions that ensures each call waits for the previous ones to complete before executing. Although I have a JavaScript implementation available, I am facing challenges in defining the type ...

Is it possible to restrict optionality in Typescript interfaces based on a boolean value?

Currently, I am working on an interface where I need to implement the following structure: export interface Passenger { id: number, name: string, checkedIn: boolean, checkedInDate?: Date // <- Is it possible to make this f ...

Guide on how to prevent click events when a checkbox is not selected in Angular 2

A click event is being used on a ul element with a checkbox below it. When the checkbox is checked, the list should be enabled and the click event should work. If the checkbox is unchecked, the list should be disabled and the click event should not work. ...

Groups of FormControls can be created using Formgroups and Form

After receiving data from an API, I aim to build a reactive form with a parent form and multiple child forms. The data that needs to be displayed in the form has the following structure: data{ "extraInformation": false "cars" ...

Contrast in output between for and for..of loops demonstrated in an example

Here are two code snippets, one using a traditional for loop and the other using a for...of loop. export function reverseWordsWithTraditionalForLoop(words: string): string { const singleWords: string[] = words.split(' '); for (let i = 0; i &l ...

Is it possible to iterate over a non-reactive array in a Vue template without having to store it in a data property or computed property?

Presented below is a static array data: const colors = ["Red", "Blue", "Green"]; To display these values in my markup, I can use the following method in React: import React from "react"; // Static array of colors const colors = ["Red", "Blue", "Green"] ...

Encountering an unusual behavior with React form when using this.handleChange method in conjunction

RESOLVED I've encountered a quirky issue with my React/Typescript app. It involves a form used for editing movie details fetched from a Mongo database on a website. Everything functions smoothly except for one peculiar behavior related to the movie t ...

The name 'Queue' cannot be located in Typescript, error code ts(2304)

I'm currently trying to create a private variable of type InnerItem, but I keep encountering the following error: Error: Cannot find name 'Queue'.ts(2304) private savedItems: Queue<InnerItem> = new Queue<InnerItem>(20); Could ...