Search code examples
javascriptvue.jspinia

Pinia reading getter from another getter


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.


Solution

  • 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