State Management in Vue 3 with Pinia

State Management in Vue 3 with Pinia

State Management in Vue 3 with Pinia

Pinia is the official state management solution for Vue 3. It provides a simple, intuitive API built on top of the Composition API, with excellent TypeScript inference and Vue DevTools support.

Step 1 — Install and Register Pinia

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

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

Step 2 — Define a Store

// stores/auth.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const user  = ref(null)
  const token = ref(localStorage.getItem('token'))

  const isLoggedIn = computed(() => !!token.value)

  async function login(credentials) {
    const res  = await fetch('/api/login', { method: 'POST', body: JSON.stringify(credentials) })
    const data = await res.json()
    user.value  = data.user
    token.value = data.token
    localStorage.setItem('token', data.token)
  }

  function logout() {
    user.value  = null
    token.value = null
    localStorage.removeItem('token')
  }

  return { user, token, isLoggedIn, login, logout }
})

Step 3 — Use in Components

<script setup>
import { useAuthStore } from '@/stores/auth'

const auth = useAuthStore()
</script>

<template>
  <div v-if="auth.isLoggedIn">
    Welcome, {{ auth.user.name }}
    <button @click="auth.logout">Logout</button>
  </div>
  <LoginForm v-else @submit="auth.login" />
</template>

Step 4 — Store Persistence with Plugin

npm install pinia-plugin-persistedstate
import { createPinia } from 'pinia'
import piniaPersistedState from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(piniaPersistedState)

// In your store
export const useAuthStore = defineStore('auth', () => { ... }, {
  persist: true, // persists to localStorage automatically
})
All Comments