Best practice for updating Pinia state? #1264
-
I'm wondering if there is a best practice, or convention for updating state in Pinia. Let's say you have some state like this: export const useExampleStore = defineStore('ExampleStore', {
state: () => {
return {
isLoaded: false
}
}
} When using Vuex, I'd dispatch an action, which would commit a mutation. My question is: In Pinia, is it still considered a best practice to update all state through actions, or is directly mutating state in components considered okay as well? Is there any convention around this? For example: const exampleStore = useExampleStore()
const { isLoaded } = storeToRef(exampleStore)
//This action is made up for the example
const { setLoadingStatus } = exampleStore
// Direct mutation of Pinia store
isLoaded.value = true
// VS
// Using a Pinia action
setLoadingStatus(false) Any thoughts / advice on this is greatly appreciate. Thank you! 🙏 |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 11 replies
-
It was rather a pattern than a best practice. In pinia you don’t create an action to just change the state. You can use $patch to directly change the state. You can directly change the state in components as well. |
Beta Was this translation helpful? Give feedback.
-
I asked @posva on twitter and he confirmed that you can do isLoaded.value = true; |
Beta Was this translation helpful? Give feedback.
-
you can change state from anywhere you want But keep in mind that if you keep all the updates in one place, it will be much easier to manage and maintain the code in the future. |
Beta Was this translation helpful? Give feedback.
-
Hi I have a question on the same here, can we use computed property here to have a 2 way binding with store and state directly? The below code is in context to the options api. Thank you for this amazing plugin. form: {
get() {
return useAppStore().appStoreVar;
},
set(value) {
useAppStore().setForm(value);
},
} |
Beta Was this translation helpful? Give feedback.
-
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useDebugStore = defineStore('debug', () => {
const enabled = ref(false)
function update(value: boolean) {
enabled.value = value
}
return { enabled, update }
}) How to denied |
Beta Was this translation helpful? Give feedback.
It was rather a pattern than a best practice.
In pinia you don’t create an action to just change the state. You can use $patch to directly change the state. You can directly change the state in components as well.