← Back to all snippets
JAVASCRIPT

Implementing Global State Management with Pinia

Discover how to set up and use Pinia, the recommended state management library for Vue 3, to create a centralized store for managing global application state efficiently.

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

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
    name: 'Pinia User',
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    greeting: (state) => `Hello, ${state.name}! Your count is ${state.count}.`,
  },
  actions: {
    increment(amount = 1) {
      this.count += amount;
    },
    decrement(amount = 1) {
      this.count -= amount;
    },
    async fetchRandomNumber() {
      this.loading = true;
      try {
        const response = await fetch('https://www.random.org/integers/?num=1&min=1&max=100&col=1&base=10&format=plain&rnd=new');
        const data = await response.text();
        this.count = parseInt(data.trim(), 10);
      } catch (error) {
        console.error('Failed to fetch random number:', error);
      } finally {
        this.loading = false;
      }
    },
  },
});

// main.js (part of app initialization)
// 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');

// Usage in a Vue Component:
// <template>
//   <div>
//     <p>{{ counter.greeting }}</p>
//     <p>Current Count: {{ counter.count }}</p>
//     <p>Double Count: {{ counter.doubleCount }}</p>
//     <button @click="counter.increment()">Increment</button>
//     <button @click="counter.increment(5)">Increment by 5</button>
//     <button @click="counter.decrement()">Decrement</button>
//     <button @click="counter.fetchRandomNumber()">Fetch Random Count</button>
//   </div>
// </template>

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

// const counter = useCounterStore();
// </script>
How it works: This snippet illustrates using Pinia for global state management in Vue 3. It defines a `counter` store with reactive `state`, `getters` for derived values, and `actions` for modifying the state, including asynchronous operations. The example demonstrates how to set up Pinia globally and access/manipulate store data within a component.

Need help integrating this into your project?

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

Hire DigitalCodeLabs