"Utilize parameter passing with mapGetters in the Vuex state management system

Hello there!

I'm currently working on a Vue.js project and using modules. I am trying to get filtered data from a getter, but I'm unsure how to provide parameters.

Specifically, I need to pass a 'name' parameter to the Getter. How can I achieve this in my Component.vue file?

/*State in vuex*/
state: {
   tempMessageValues: [
            { name: 'RU', status: 'none', selected: false },
            { name: 'BY', status: 'none', selected: false },
            { name: 'KG', status: 'none', selected: false }
        ]
}

/*Getters*/

import * as types from '../types';

export default {
    [types.GETTERS.TEMP_MESSAGE_VALUES]: state => {
        return state.tempMessageValues.find(country => country.name === name);
    }
};

/*Types*/

export const GETTERS = {
    TEMP_MESSAGE_VALUES: 'shared/TEMP_MESSAGE_VALUES'
};

/*Code in Component.vue*/

import * as types from "./store/types";
import { mapGetters } from "vuex";

export default {
  computed: {
    ...mapGetters({
      getTempMessValues: types.GETTERS.TEMP_MESSAGE_VALUES
    })
  }
};

Answer №1

The documentation recommends utilizing currying to pass parameters to a getter function;

export default {
  [types.GETTERS.TEMP_MESSAGE_VALUES]: state => name =>
    state.tempMessageValues.find(country => country.name === name)
};

Refer to https://vuex.vuejs.org/guide/getters.html#method-style-access for an illustration of this concept. Essentially, you are creating a function that is returned by the getter when it is first called.

Is this explanation clear?

Answer №2

One way to enhance the getter is by returning a function that allows you to pass a parameter.

export default {
[types.GETTERS.TEMP_MESSAGE_VALUES]: state => {
    return (name) => state.tempMessageValues.find(country => country.name === name);
}
};

Now, simply call your function and pass in the parameter to access your getter:

this.getTempMessValues('YourValue')

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 can I use a JavaScript function to remove an element from a PHP array?

Imagine I have a PHP session array: $_SESSION[MyItems]=Array('A'=>"Apple", 'B'=>"Brownie", 'C'="Coin")) which is utilized to showcase items on a user's visited page. I want the user to have the ability to remove o ...

What should I designate as the selector when customizing dialog boxes?

I am attempting to change the title bar color of a dialog box in CSS, but I am running into issues. Below is the HTML code for the dialog box and the corresponding CSS. <div id="picture1Dialog" title = "Title"> <p id="picture1Text"> ...

Navigating through paginated data can be made easier by using Backbone.PageableCollection in conjunction with a personalized

I have developed an application that interacts with a database known as LeanCloud. Currently, I have configured a page to display all the users stored in the database. However, LeanCloud has a limitation where only 100 pieces of data can be retrieved per r ...

Utilizing AngularJS and RequireJS to incorporate a controller into the view

I am facing an issue while trying to add an Angular controller to my HTML view. Typically, in Angular, this can be done using: ng-controller="<controller>". However, due to my use of RequireJS, I have had to implement it differently. I need to includ ...

The issue arises when attempting to make an Ajax request after changing the value of a cascading dropdown

Hey there! I'm currently working on a cascading drop-down feature where, upon change, I need to populate another field with data from the database. Unfortunately, every time I try to populate the drop-down, my AJAX call returns an error 500. I can&ap ...

Server blocking access to Javascript files

Having some trouble with my code, it works fine on Localhost but not on Fasthosts server. Seems to be an access issue to a folder on the server, here are the debug messages: GET (http://reggarockaboogie.co.uk/images/gallery/fld01/) 403 (Forbidden) k.cors ...

Creating an event emitter instance

I'm intrigued by the process of objects transitioning into event emitters. The documentation showcases code that resembles the following: var EventEmitter = require('events').EventEmitter; function Job(){ EventEmitter.call(this); } I fi ...

What could be causing my Node application to give a 404 error when making a POST request?

I'm at a loss trying to debug my app for what seems like a simple error, but I just can't locate it. Here is an overview of how my Express app is structured. My routes are set up as follows: var routes = require('./routes'); ... app.g ...

"Error: Unable to push new Grade to grades array" encountered while attempting to add a Grade to an existing array

Hi there! I'm working on a webapp that allows me to track my grades and calculate the average, but I'm having trouble adding grades to my Array using a button. Whenever I click on the Add Button, an error message pops up: TypeError: this.grades. ...

Error Encountered in MERN Stack Development: TypeError Thrown Due to Inability to Convert Undefined

Currently, I am following the MERN Stack, Front To Back Course by Traversy Media. I am in the process of setting up the login functionality for the application. Despite ensuring that my code matches his exactly, I am encountering an error: TypeError: Canno ...

The $watch() function seems to be failing to properly refresh the $scope

Within my controller, I have a function $scope.remove() that triggers a request to the usercart, which then calls an API. The JSON response from the API includes an object with an array of cart items. Despite using an ng-repeat in the HTML to iterate thro ...

Remove item from jQuery's "raw text" HTML

Suppose I have the following JavaScript string: var string = '<div id="div1"><div id="div2"></div></div>'; Is it possible to utilize jQuery in order to create a new string as shown below? var newString = '<div i ...

Possible issue with accurate indexing causing caption error with API images in React

Continuing from: Implementing a lightbox feature in react-multi-carousel for my ReactJS app My application utilizes react-images for the lightbox functionality and react-carousel-images for the carousel. The API provides a title and image data. The issue ...

Vue fails to trigger a rerender of the list, even when the set function is utilized

I created a list where each item can be removed, and this is how my code looked: Snippet <template v-for="(timeFrame, index) in form.timeFrames"> <el-form-item > ...

Tips for utilizing import alongside require in Javascript/Typescript

In my file named index.ts, I have the following code snippet: const start = () => {...} Now, in another file called app.ts, the code is as follows: const dotenv = require('dotenv'); dotenv.config(); const express = require('express' ...

Laravel vue infinite scroll failing to load additional content

I've been trying to implement the infinite scroll feature from Element UI in my app, but for some reason, it's just not working. Here's a snippet of my code: Code script // Your JavaScript code goes here ...

jQuery failing to trigger onClick event for a specific group of buttons

Javascript: <script> $(document).ready(function(){//Implementing AJAX functionality $(".acceptorbutton").on('click', function(){ var whichClicked = this.attr('name'); ...

Encountering obstacles with asynchronous requests while attempting to retrieve an Excel file using ajax

I am coding JavaScript for a SharePoint project, focusing on creating a function to retrieve data from an Excel document in a library. While I have successfully implemented the basic functionality, I am facing an issue with large file sizes causing the dat ...

Struggling to retrieve an element from an object received through a get request in Express

I am facing an issue with a get request that returns an array of objects retrieved from a database using Knex. I am trying to use .map to make these objects accessible, but I am struggling with accessing the final element which is a sum(). It seems like a ...

Creating a JSON hierarchy from an adjacency list

I am currently working with adjacency data that includes ID's and Parent ID's. My goal is to convert this data into hierarchical data by creating nested JSON structures. While I have managed to make it work, I encountered an issue when dealing ...