When initializing state on a Vue 3 (composition API) Pinia store which pattern is more "correct" or idiomatic?
Option 1:
state: () => ({
user: {},
}),
Option 2:
state: () => {
return {
user: {},
};
},
Option 3: Maybe something else?
They are the same. Option 1 and 2 are functions that returns an object. In arrow functions, the { stands for the content of the function (like function x () {). So if you want to return an object (like return {), you would use ({ as option 1 does.
Reference: Arrow functions advanced syntax
For the Vue 3 Composition API in Pinia, the correct pattern is:
export const useUserStore = defineStore('users', () => {
const user = ref({});
return { user };
})
It's called "Setup Store".
In Setup Stores:
ref()s becomestateproperties
computed()s becomegetters
function()s becomeactions
More info: https://pinia.vuejs.org/core-concepts/#setup-stores
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With