It was highlighted by Phil that the getters
feature should not modify the state in any way. Since Pinia does not support mutations, it is recommended to utilize actions
instead.
Furthermore, Arrow functions are designed to lack a reference to this
. Therefore, if you need to access any other store methods or variables within the state, it is advisable to create an action using standard JavaScript function syntax, such as:
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
},
},
})
Subsequently, in any external file where the defined store has already been imported, simply call the action as follows:
import { useUserStore} from '~/stores/user'
const store = useUserStore()
store.setName('Tom')
Please take note that in Pinia actions, it is highly encouraged to consistently employ regular JavaScript function syntax since they are responsible for altering data within your state.