Search code examples
javascriptvue.jspinia

Accessing a getter from a parameterized getter


tl;dr

How to access other getters from a parameterized getter? Normally, you can use this.myGetter; but a parameterized getter is implemented as an arrow function, wherein this is undefined. What's the preferred way to handle this case in Pinia?


I'd like to create a parameterized getter (multiSum) in my Pinia store, which accesses another getter (sum).

Getters can be accessed via this, but that won't work from within an arrow function which is used to implemented a parameterized getter: multiSum crashes because this is undefined in the context of the nested arrow function.

getters: {
  sum: (state) => state.a + state.b,
  multiSum: (state) => (count) => this.sum * count // crash: this is undefined
}

In Vuex, parameterized getters can access other getters via a parameter instead of this, which also works in arrow functions. But afaik this API does not existing in Pinia.

I can work around this by capturing the store instance:

multiSum(state) {
  const store = this
  return (count) => store.sum * count
}

This works, but is pretty verbose. Is there a better (more framework-compliant) way to do this?


Solution

  • this can be undefined inside arrow function because it's not interchangeable with regular function and gets a context from parent scope.

    The usage of this and state is explained in details in the documentation. Either this or state can be used, but this has better Typescript and thus IDE support.

    In the first snippet, state is already available in function scope, there is no need to access this:

    multiSum: (state) => (count) => state.sum * count
    

    In the second snippet, const store = this isn't needed because a store is already this.

    multiSum() {
      return (count) => this.sum * count
    }