Using Typescript, a vuex getter that includes an argument can be implemented to

Have you ever wondered how to create a Vuex store getter that takes a parameter argument? Check out this example: https://vuex.vuejs.org/en/getters.html

I'm currently working on a project using Typescript (https://github.com/hmexx/vue_typescript_starter_kit), and I'm facing a challenge in writing a getter that accepts a parameter argument. The code snippet below illustrates my attempt, but it doesn't seem to work as expected:

export function getItemById(state : State, id : Number) : MyItem | undefined     {
  if(id === undefined) {
    return undefined;
  }
  for(const item of state.items) {
    if(item.id === id) {
      return item;
    }
  }
  return undefined;
}

export default <GetterTree<State, any>> {
  getItemById
};

Answer №1

According to the documentation on vuex, you can incorporate the following:

getters: {
  // ...
  getTaskById: (state, getters) => (id) => {
    return state.tasks.find(task => task.id === id)
  }
}
store.getters.getTaskById(2) // -> { id: 2, description: '...', completed: false }

In TypeScript, a similar approach could look like this:

export default {
  getItemById(state: State, getters: any) {
    return (id: number) => {
      return state.items.find(item => item.id === id);
    }
  }
}

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

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...

Receiving API response with a format similar to JSON, but encountering an issue during the parsing process

My API is returning the following: {"permissions": [{"id":1,"product_id":10,"permission_type":"ADD","name":"Add"}, {"id":2,"product_id":10,"p ...

Using Systemjs with Angular 2 results in 50 server calls for loading resources

While following the Angular2 quickstart tutorial on Angular.io, I noticed that it was making 50 separate requests, which left me wondering why. Is there a way to consolidate all these requests into one? My goal is to have a maximum of 8 bundles. This is ...

The element 'Component' is not eligible to be utilized as a JSX component (typed layout)

I encountered a type error while working with the following code snippet: {getLayout(<Component {...pageProps} />)} The error message states that 'Component' cannot be used as a JSX component. This is because its element type 'Compo ...

Do you think it's wise to utilize React.Context for injecting UI components?

I have a plan to create my own specialized react component library. These components will mainly focus on implementing specific logic rather than being full-fledged UI components. One key requirement is that users should have the flexibility to define a se ...

Definition of a Typescript Global.d.ts module for a function that is nested within another function

Simply put, I have a npm module that exports a function along with another function attached to it: // @mycompany/module ... const someTool = (options) => { // do some cool stuff }; someTool.canUseFeature1 = () => { return canUseSomeFeature1(); ...

Ways to simulate a function that is a part of an internal object

Is there a way to mock a method from an object within my UnderTest class? When the Update method is triggered by an event from a child component, I need to mock the service.saveNewElement(data) method in order to test data in the then() block. <script ...

Angular 11 along with RxJS does not support the combineLatest method in the specified type

Hey there, I'm currently working on utilizing the combineLatest operator to merge two streams in Angular, but I keep encountering an error message stating that "combineLatest does not exist on type". I've attempted to move the code into a .pipe() ...

Developing a separate NPM package for a portion of the app causes an increase in the total app size

Our projects utilize create-react-app and Typescript, resulting in the emergence of a collection of commonly used React components. To enhance maintenance and reusability, we decided to extract these components into their own NPM package named PackageA. Su ...

Using the timer function to extract data within a specific time frame - a step-by-step guide

Is there anything else I need to consider when the temperature increases by 1 degree? My plan is to extract data from my machine for the last 30 seconds and then send it to my database. set interval(function x(){ If(current_temp != prev_temp){ if((c ...

`Achieving efficient keyboard navigation with MUI Autocomplete and SimpleBar integration in React``

Currently, I am attempting to integrate the Simplebar scrollbar into the MUI Material Autocomplete component in place of the default browser scrollbar. While everything is functioning correctly, this customization has caused me to lose the ability to use t ...

What is the best way to transform a Storybook typescript meta declaration into MDX format?

My typescript story file is working fine for a component, but new business requirements call for additional README style documentation. To meet this need, I am trying to convert the .ts story into an .mdx story. However, I am facing challenges in adding de ...

Is it possible to access the service and 'self' directly from the HTML template?

When working with Angular 6, one method to access component properties from a service is to pass 'self' to the service directly from the component. An example of this implementation is shown below: myComponent.ts public myButton; constructor(p ...

Activate function on Ctrl + K in a React TypeScript project

I am currently developing a React TypeScript application using version v18.2.0. My goal is to trigger a function when the user simultaneously presses Ctrl + K. Here is the code snippet within my component: const keyDownHandler = (event: KeyboardEvent) =& ...

Executing mocha using Typescript results in a TypeError [ERR_UNKNOWN_FILE_EXTENSION] because the file extension ".ts" is unrecognized

I've been experimenting with Typescript and Mocha to write some tests. After following the documentation, I've set up the following: package.json { //... "scripts": { "test": "mocha", }, //... } .mocharc.j ...

What are the best practices for transpiling code using Parcel-bundler?

Currently, I am attempting to transpile both .ts (TYPESCRIPT) and .scss (SASS) files. However, I am encountering two main issues: 1) Instead of generating my file in the designated dist directory, it is creating a dist directory within the build folder. ...

Executing multiple service calls in Angular2

Is there a way to optimize the number of requests made to a service? I need to retrieve data from my database in batches of 1000 entries each time. Currently, I have a loop set up like this: while (!done) { ... } This approach results in unnecessary re ...

Learn how to manually trigger the opening of ngx-popover in Angular 2

I have implemented ngx-popover in my project. I am attempting to trigger it from a different component using a button click. Second Component HTML: <button popover #ChatPopover=popover (click)="ClickElement()"> <span class="glyphicon glyphico ...

What is the reason behind material-ui's decision to invoke their dialogs twice?

After attempting to implement a modal and realizing the strange behavior, I switched to using a dialog instead. To my surprise, the issue persisted. This is how I approached it: import Dialog, { DialogProps } from '@material-ui/core/Dialog'; imp ...

The SonarQube code coverage differs from that of Jest coverage

I'm struggling to grasp why SonarQube and Jest coverage results differ so significantly. SonarQube coverage resultshttps://i.sstatic.net/dodGi.png Jest coverage https://i.sstatic.net/uYKmt.png https://i.sstatic.net/rakzw.png https://i.sstatic.net/ ...