0

I have a store in Pinia (using Vue 3), that often uses getters that reference other getters. I've been using state.getterName to reference, and it's been working but sometimes warns me the getter does not exist. I somehow missed in the docs that I should be using this. when referencing a getter within another getter.

This is what I'm currently doing:

const useMyStore = defineStore('myStore', {
    state:() =>({
        state1: 100
    }),
    getters: {
        getterName1: (state) => {
           return state.state1 * 100
        },
        getterName2: (state) => {
           return state.getterName1 - 100
        }
    }
})

I think I should be doing this:

const useMyStore = defineStore('myStore', {
    state:() =>({
        state1: 100
    }),
    getters: {
        getterName1: (state) => {
           return state.state1 * 100
        },
        getterName2: () => {
           return this.getterName1 - 100
        }
    }
})

My question is: why does incorrectly using state.getterName work? What risks do I add by not using this? Should I refactor my store to use this?

Adding in this discussion in case it adds context. Also wanted to mention I'm not using TypeScript, so I can't force the return type.

Yolo_chicken
  • 1,221
  • 2
  • 12
  • 24
  • 1
    Possible duplicate of https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable – Estus Flask Apr 12 '23 at 17:03
  • 1
    You're misusing an arrow, you won't find it be used together with `this` if you follow the guides. I'm quite sure that you're limited to using the state and not getters when you use state.getterName, at least with TS – Estus Flask Apr 12 '23 at 17:05
  • Any idea why it's letting me use getters when I use `state`? I'm not using TS. – Yolo_chicken Apr 12 '23 at 17:11
  • 1
    Likely because `state` is the whole store in this case, but since it's not documented, it's not a good thing to do – Estus Flask Apr 12 '23 at 17:14

1 Answers1

0

I can offer you an alternative, Vue 3 works much better with Composition APi, faster, more intuitive and easier to understand, this is how I handle it and it does not cause conflicts and little by little your application is scaling

import { defineStore } from 'pinia'
import { ref } from 'vue

export const useMyStore = defineStore('myStore',() => {
const state1 = ref(100);

const getterName1 = () => state1.value * 100
const getterName2 = () => state1.value - 100

return {state1,getterName1, getterName2}
})

and now you can use it in any component like this

import {useMyStore} from 'yourpath/'
const useStore = useMyStore

const test = () => {
useStore.getterName1()
}

<template>
<p>{{useStore.state1}}</p>
</template>

hope helpfull

  • This would work but would actually mean that the function is now an `action` instead of a `getter`. To have it be a `getter`, you should make it `computed` – Guy Passy Jun 15 '23 at 08:49