Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way of setting state on a Vue 3 Pinia store?

Tags:

vue.js

pinia

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?

like image 598
TinyTiger Avatar asked Nov 02 '25 10:11

TinyTiger


2 Answers

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

like image 135
Bernardo Dal Corno Avatar answered Nov 05 '25 16:11

Bernardo Dal Corno


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 become state properties

computed()s become getters

function()s become actions

More info: https://pinia.vuejs.org/core-concepts/#setup-stores

like image 42
Dmytro Lisunov Avatar answered Nov 05 '25 15:11

Dmytro Lisunov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!