The function Getter is expected, but an error has occurred with "getters.doubleCounter" returning a value of 20 in VUEX

Currently, I am diving into the world of Vuex and encountering some challenges along the way. In my attempt to create a getter on my vuex instance, I am facing an error when trying to display data from one of my components:

The getter should be a function but instead "getters.doubleCounter" is showing as 20.

store.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    counter: 10
  },
  getters: {
    doubleCounter: state => {
      return state.counter * 2;
    }
  }
});

MY COMPONENT:

<template>
  <div>
    <p>This message is from services.</p>
    <button v-on:click="increment">+</button>
    <button v-on:click="decrement">-</button>
    {{ counter }}
  </div>
</template>

<script>
  export default {
    computed: {
      counter() {
        return this.$store.getters.doubleCounter;
      },
    },
    methods: {
      increment: function () {
        this.$store.state.counter++
      },
      decrement: function () {
        this.$store.state.counter--
      }
    }
  }
</script>

Once again, upon attempting to render the page containing this component, it fails and displays the aforementioned error message in the console. Any assistance would be immensely appreciated! Thank you!

Answer №1

Give this a shot.

multiplyByTwo: (num) => {
      return num * 2;
    }

Answer №2

It's unclear what is causing the error in your situation, but it's important to avoid directly manipulating the state outside of a mutation function.

Your code should never assign anything directly to a state property. For instance, the following is not recommended:

this.$store.state.doubleCounter++

Instead, here is the correct approach:

Vue.component('counter', {
  template: `
  <div>
    <p>This message is from services</p>
    <button v-on:click="increment">+</button>
    <button v-on:click="decrement">-</button>
    {{ counter }}
  </div>
  `,
  computed: {
    counter() {
      return this.$store.getters.doubleCounter;
    },
  },
  methods: {
    increment: function () {
      this.$store.commit('increment')
    },
    decrement: function () {
      this.$store.commit('decrement')
    }
  }
})

const store = new Vuex.Store({
  state: {
    counter: 10
  },
  mutations: {
    increment(state) { state.counter++ },
    decrement(state) { state.counter-- }
  },
  getters: {
    doubleCounter: state => {
      return state.counter * 2;
    }
  }
})

new Vue({
  el: '#app',
  store
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7600031336445843584745">[email protected]</a>/dist/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="790f0c1c01394a57495748">[email protected]</a>/dist/vuex.js"></script>
<div id="app"><counter/></div>

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

Transferring information among components and incorporating the ngDoCheck function

We are currently working on transferring data from one component to another using the following method. If there is no data available, we display an error message; however, if there is data present, we populate it in a select box. showGlobalError = true; ...

From Vanilla Javascript to ES6 Spread Operator

I recently incorporated a script into my project that utilizes the ES6 spread operator to extract parameters from the URL. However, I encountered an issue when I realized that the project does not support ES6 syntax. While it is straightforward to apply t ...

What is the best way to manage asynchronous data within AngularJS directives?

Having encountered similar challenges to this specific scenario, I am currently facing issues with handling asynchronous data within my directives. The main issue arises when trying to pass asynchronously fetched data into these directives. Initially, I at ...

React error: Unable to use 'in' operator to find 'length' in null

I am trying to access and filter a local array file, then store the filtered array as a state before passing it to a child component. // Sample array file const originalData = [ { "ComName":"A", "SDGs":"1", " ...

Verify if the button is assigned a specific class, then generate a 'completed' div

I'm new to working with Jquery and I have a question. In my upload form, when something is uploaded the upload-button changes class from: <a class="upload-button upload buy" id="upload-button"><span>Upload a document</span></a> ...

Dynamic links with Node Acl

Utilizing the npm module Acl to establish an ACL system has been my current focus. You can check out the homepage of this module at: https://github.com/OptimalBits/node_acl. While the documentation provides straightforward examples for granting role acces ...

What is the best way to randomly display an image from a JavaScript array within an HTML document?

I currently have this code in my HTML and JavaScript files, but I am having trouble with displaying images without using a URL in the JavaScript file. The images are located in my project folder. However, when I open the HTML file, the images do not appear ...

Exploring the possibilities with a Nuxt Site as a foundation

[![enter image description here][1]][1] Exploring the world of nuxt and vue, I aim to build a basic website using vue and then convert it into a static site utilizing: nuxt generate I have successfully accomplished this task with nuxt and vuetify (check ...

Using AngularJS location.path for unique custom URLs

Control Code: $scope.$on('$locationChangeStart', function () { var path = $location.path(); var adminPath = '/admin/' ; if(path.match(adminPath)) { $scope.adminContainer= function() { return true; }; }); HTML <div clas ...

Looking for assistance in resolving the error message: 'state' is not defined no-undef

I'm having some trouble adding a navbar to one of my projects as I keep encountering a failed to compile error. "Line 7:5: 'state' is not defined no-undef Line 9:5: 'handleClick' is not defined no-undef" import React, { ...

An array in JSON format containing only one element

I am currently working on a project that involves JSON format output. I am in need of some clarity regarding the structure of JSON arrays. Specifically, I'm curious about how to handle fields that allow multiple entries in an array format. In cases wh ...

Issue with Repeated String Test in JavaScript: Single Failure Detected

Currently tackling the Repeated String Challenge on HackerRank. The challenge description goes as follows: A string, denoted by s, consisting of lowercase English letters is repeated infinitely. With an integer, n, the goal is to determine and output the ...

Error thrown: Uncaught TypeError - Attempted to access 'params' property of undefined object in the context of StudentDetails

I've encountered an issue where I need to transfer student application data from my server-side to my client-side. Whenever a new student application is created, I want to display their information on my StudentDetails.jsx file. Here is my Server.js c ...

Execute a function on every item within a loop by utilizing jQuery

My view-model includes a data grid similar to the one displayed below <table> @foreach (var item in Model) //for(int i=0;i<Model.Count();i++) { using (Html.BeginForm("Edi ...

Highcharts memory leakage issue arises when working with jQuery version 2.X

After extensive testing on my AngularJS application, I have discovered a memory leak when using Highcharts with the latest version of jQuery (2.1.4). Below are links to two plunkers for comparison: Using jQuery 1.8.2: http://plnkr.co/edit/lQ6n5Eo2wHqt35OV ...

How can I efficiently add multiple items to an array and store them in async storage using React Native?

I am trying to store multiple elements in local storage using React Native. I found some helpful documentation on how to do this here. Could someone guide me on the correct way to achieve this? Here's a snippet of my code: My current approach const ...

Issue with validation in Vue using vue-signature-pad was encountered

Greetings! As a newcomer, I humbly present my first question, so please be gentle. Prior to reaching out with this query, I scoured every corner in search of a solution but unfortunately came up empty-handed. In Vue with Vuetify, I've crafted a strai ...

Sending the axios fetched property from the parent component to the child component results in the error message "TypeError: Cannot read property 'x' of undefined"

I've noticed that this question has been asked before, but none of the solutions provided seem to work for my situation. Parent component import axios from "axios"; import { useEffect, useState } from "react"; import Child from &q ...

Retrieve information from individual XML nodes in a parsed string

When making an Ajax call to retrieve XML data from a different domain using a PHP proxy to bypass cross-origin restrictions, I am unable to extract the values from the XML nodes and display them in my HTML tags. Despite no errors showing up in the browser ...

What are some methods to prevent cookies from being overridden?

Just beginning my journey in web development. Currently utilizing asp.net Web API and Angular with token authentication. Every time a user logs in, I set the token in a cookie and send it with each request. Everything has been running smoothly so far, bu ...