JAVASCRIPT

Centralized Global State Management with Pinia

Learn how to set up and use Pinia, the recommended state management library for Vue 3, to manage global application state like user authentication or shopping cart data efficiently.

// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const app = createApp(App)
app.use(createPinia())
app.mount('#app')

// stores/userStore.js
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    isAuthenticated: false,
    username: null,
    token: null
  }),
  getters: {
    isLoggedIn: (state) => state.isAuthenticated && state.token !== null
  },
  actions: {
    login(username, token) {
      this.isAuthenticated = true
      this.username = username
      this.token = token
      // Potentially persist to localStorage here
    },
    logout() {
      this.isAuthenticated = false
      this.username = null
      this.token = null
      // Clear from localStorage here
    }
  }
})

// components/AuthStatus.vue
<template>
  <div>
    <p v-if="userStore.isLoggedIn">Welcome, {{ userStore.username }}!</p>
    <p v-else>Please log in.</p>
    <button @click="userStore.login('vueUser', 'fake-jwt')" v-if="!userStore.isLoggedIn">Login</button>
    <button @click="userStore.logout()" v-if="userStore.isLoggedIn">Logout</button>
  </div>
</template>

<script setup>
import { useUserStore } from '@/stores/userStore'

const userStore = useUserStore()
</script>
How it works: This snippet demonstrates integrating Pinia for global state management in a Vue 3 application. It sets up a basic `userStore` to manage authentication status, username, and a token. The `main.js` file installs Pinia. The `userStore.js` defines a store with state, getters for derived state (like `isLoggedIn`), and actions for modifying the state (e.g., `login`, `logout`). A component then uses `useUserStore()` to access and interact with the global state, allowing for consistent data across the entire application without prop drilling.

Need help integrating this into your project?

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

Hire DigitalCodeLabs