JAVASCRIPT

Efficient Global State Management with Pinia in Vue 3

Learn to set up and use Pinia for robust, type-safe, and modular global state management in your Vue 3 applications, enhancing maintainability.

// stores/counter.js
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
    name: 'Eduardo'
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    // can use 'this' if not arrow function to access other getters
    // doubleCountPlusOne() {
    //   return this.doubleCount + 1
    // }
  },
  actions: {
    increment() {
      this.count++;
    },
    async incrementAndFetchUser() {
      this.increment();
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 500));
      this.name = 'Fetched User';
    }
  }
});

// main.js (part of app setup)
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';

const app = createApp(App);
const pinia = createPinia();

app.use(pinia);
app.mount('#app');

// SomeComponent.vue
<template>
  <div>
    <p>Count: {{ counter.count }}</p>
    <p>Double Count: {{ counter.doubleCount }}</p>
    <p>User Name: {{ counter.name }}</p>
    <button @click="counter.increment()">Increment</button>
    <button @click="counter.incrementAndFetchUser()">Increment & Fetch</button>
  </div>
</template>

<script setup>
import { useCounterStore } from './stores/counter';

const counter = useCounterStore();
</script>
How it works: This snippet demonstrates how to use Pinia, the official state management library for Vue 3. It shows defining a store with `state`, `getters`, and `actions`, then integrating Pinia into your Vue app. Finally, it illustrates how to access and modify the store's state within a component using the `useCounterStore` composable, enabling robust global data flow.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs