Exploring methods to retrieve data from an array in a Vue store through Getters

I am currently facing an issue where I am attempting to include an argument within getters in order to retrieve the ID of the permissions, but unfortunately it is not returning any results.

////STATE
state: { 
  permissions: [
    {id: 1, name: 'Create User'},
    {id: 2, name: 'Delete User'},
    {id: 3, name: 'UpdateUser'}
   ] 
  }
//// GETTERS
getters: {
  getPermissionById: state => id => {
    return state.permissions.find(p => p.id=== id) // I attempted using "=="
  }
}

Instead of the desired result, I am receiving getPermissionById:ƒ (id). I'm uncertain about what I may have overlooked.

Within the component:

computed: {  

...mapGetters('permissionStore', ['getPermissionById'])
}

I am utilizing Vue Devtools to inspect the state.

Answer №1

Here's a suggested solution:

computed: {  
  ...mapGetters('permissionStore', ['getPermissionById']),
  permissionData() {
    return this.getPermissionById(this.id)
  }
},

Answer №2

This conversation was previously addressed in this thread where insights were provided by Linus Borg.

Instead of complicating things, consider using a getPermissions getter to directly fetch the permissions array from the state. Within your component's computed "permission" method, you can then do:

return this.getPermissions.find(x => x.id === this.id) 
  ? this.getPermissions.find(x => x.id === this.id).id
  : someFallback

// Alternatively, with optional chaining...

return this.getPermissionsArray.find(x => x.id === this.id)?.id || someFallback

If requiring a shared function like getPermissionsById, it might be beneficial to create a vuex action that accesses the state through the getter.

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

Resolve feature for UI routes fails to function upon refreshing the page

My app utilizes UI Route for view routing. When accessing /berlinerliste/, a function is triggered to display an array of objects. If one of these objects is clicked, the view changes to /berlinerliste/{id}/ and shows the details of that specific object. ...

Angular has the capability to rewrite URLs in CSS, providing a unique way

An issue arises in Angular when using a base set and html5mode with SVGs. This causes things like filter: url(#url) to be rewritten as filter: url(/base/#url). https://github.com/angular/angular.js/issues/8934 Disabling html5 mode and removing the base d ...

Methods for incorporating JSON Data into ChartJS

Below is my app.js file: app.js var app = angular.module('myApp', []); app.controller('MainCtrl', function($scope, $http) { $http.get('http://happyshappy.13llama.com/wp- json/llama/v1/stats').then(function(response) ...

The time format you have specified is not supported

Attempting to use the most basic moment test, but encountering issues. The following steps were taken: npm install moment In app.js file, I included the following: var moment = require('moment'); var testDate = new Date(); console.log(moment( ...

Generate and store text inputted from contenteditable

As I embark on creating my own custom rich text editor, I have a couple of questions regarding its functionality. First and foremost, is it possible to prepopulate the text area with content? Additionally, I'm seeking guidance on how to save and utili ...

Error in Javascript: Character class range is not in order

My regular expression (regex) seems to be incorrect: var domain = "google\.com\.br"; var reEmail = new RegExp("^([A-Za-z0-9_\-\.])+\@" + domain + "$"); I am trying to use this regex to validate an email address. Here is an exampl ...

Unable to use the res.send() function

I've been working on a Node.js project. Within the validate.js file, I have defined a class Validate with a static method validateTicket and exported the class at the end. validate.js file const request = require("request"); const config = { urlBas ...

Adding the current date and time to a fabric js canvas: a step-by-step guide

Looking to dynamically display the current date and time on a canvas area. The current date and time can be added using an object. However, I am facing an issue where the date and time value does not update continuously. Can anyone suggest how to achieve t ...

The term "this" in the global scope versus within a function in the Node.js environment

console.log(this) // {} function abc(){ console.log(this) } abc() // global The concept of this can vary between the global space and inside a function in Node.js. console.log(this === module.exports) // true function abc(){ ...

Comparison of Transform plugin and Syntax plugin within Babel

I am interested in incorporating Class properties into my webpack configuration. While following a tutorial on the website (www.survivejs.com), I came across two plugins being added to the .babelrc file: babel-plugin-syntax-class-properties and babel-plugi ...

Using external VB script (IE automation) to invoke Java Script on a webpage

On a webpage, there is a functionality where a checkbox can be clicked to select all the checkboxes below it. This is accomplished by invoking a JavaScript function on click. However, when attempting to select that checkbox using VBScript with .getElement ...

The MEAN.JS platform encountered an issue with the Route.all() function, as it was expecting a callback function but instead

I am currently exploring the MEAN Stack and have been experimenting with meanjs.org yo generator in version 4.1. The CRUD example was included in the generated app, which I utilized as a reference for my own code. Upon execution, I encountered the followi ...

The plugin 'vue' specified in the 'package.json' file could not be loaded successfully

There seems to be an issue with loading the 'vue' plugin declared in 'package.json': The package subpath './lib/rules/array-bracket-spacing' is not defined by the "exports" in C:\Users\<my_username>\Folder ...

Having trouble loading the Javascript file after redirection?

After a redirect in my ASP.NET Core web app, I noticed that my custom JavaScript file does not get loaded. It is included at the bottom of the _layout.cshtml page. <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/j ...

Issues with PHP ajax causing database insertion failure

Here is the code for making an AJAX request: AJAX var date = new Date().toLocaleTimeString(); var text=this.value; var id=1; $.ajax({ type: "GET", url: "StoreMessages.php" , data: { room: id, msg:text, sendat:date } }); PHP Code if(isset($_GET['r ...

Is it possible to add items to your cart based on a matching product ID?

My challenge is to add an item to a list only if it matches the id, ensuring that only one item is added to the cart. I've attempted various methods but React doesn't seem to recognize my item's id. Below is the code excerpt where I'm ...

Guide to utilizing import and export features in node.js

My issue involves two specific files: The first file, app.js The second file, module.js In app.js, there is an expression that looks like this: import 'foo' from './module' //use foo.. Meanwhile, module.js contains the following: ...

Verify whether the element within an iFrame contains any content

After conducting extensive research, I have been unable to find a satisfactory answer to my question. Therefore, I am reaching out to see if anyone has the knowledge I seek. The Goal: I aim to check the contents within an iFrame and determine whether it ...

Can you clarify the distinction between calling subscription.unsubscribe() and subscription.remove()?

Currently, I am working with Angular 5 and have successfully subscribed to an observable with the use of the subscribe() method. My concern pertains to whether simply calling the unsubscribe() method on the subscription will be adequate for cleaning up all ...

Converting XML to JSON using UTF-8 Encoding

I am currently working with xml2js to convert an XML feed into JSON format. However, I'm facing an issue where certain characters like Æ, Ø & Å are displayed as expected in the XML but appear differently after parsing. After parsing, I receive ...