'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
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Johann Garrido |
