tony
tony

Reputation: 315

Vue Pinia access other function in getters with arrow functions

example store

  getters: {
    setName: (state) => (string: string) => {
      state.user.username = string;
    },
    setUser: (state) => {
      setName('Tom'); // setName is undefined.
    }
  }

Is there any way to access the setName inside an arrow function?

Example only show you can get this inside normal functions https://pinia.vuejs.org/core-concepts/getters.html#accessing-other-getters

Upvotes: 1

Views: 14457

Answers (1)

Johann Garrido
Johann Garrido

Reputation: 459

First of all, as Phil pointed out, getters feature should not mutate the state. As mutations are not included in Pinia, actions is the way to go.

Also, Arrow functions are meant to not have a this object reference. So, If you want to access any of the other store methods or variables in the state you should create an action with a regular javascript function syntax, like

import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
  state: (): myState => ({
    user: {name: 'myname'},
  }),
  getters: {
    getName: (state: myState) => state.user.name,
  },
  actions: {
    setName(newName: string) {
      this.user.name = newName
    },
  },
})

Then in any external file where you already imported the defined store, call the action just like this

import { useUserStore} from '~/stores/user'
const store = useUserStore()
store.setName('Tom')

Note: In Pinia actions you may want to always use regular javascript function syntax as those are in charge of changing data in your state.

Upvotes: 8

Related Questions