Kurs Vue.js · Moduł 11: Pinia

Actions w Pinia

3 min czytania ·
W tej lekcji4

Actions to funkcje modyfikujące state i wykonujące operacje - jak komendy kontroli misji NOVA LAB. To tu znajduje się logika biznesowa: pobieranie danych, walidacja, obsługa błędów.

Podstawowe actions

W Composition API actions to zwykłe funkcje:

import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCrewStore = defineStore('crew', () => {
  const members = ref([])
  const selectedMember = ref(null)

  // Prosta action
  function selectMember(member) {
    selectedMember.value = member
  }

  // Action z logiką
  function addMember(member) {
    if (members.value.length >= 8) {
      throw new Error('Maximum crew size reached!')
    }
    members.value.push({
      ...member,
      id: Date.now(),
      joinedAt: new Date()
    })
  }

  function removeMember(id) {
    members.value = members.value.filter(m => m.id !== id)
    if (selectedMember.value?.id === id) {
      selectedMember.value = null
    }
  }

  return { members, selectedMember, selectMember, addMember, removeMember }
})

Asynchroniczne actions

Actions mogą być asynchroniczne - idealne do pobierania danych z API:

export const useCrewStore = defineStore('crew', () => {
  const members = ref([])
  const isLoading = ref(false)
  const error = ref(null)

  async function fetchCrew() {
    isLoading.value = true
    error.value = null

    try {
      const response = await fetch('/api/crew')
      if (!response.ok) {
        throw new Error('Failed to fetch crew data')
      }
      members.value = await response.json()
    } catch (e) {
      error.value = e.message
    } finally {
      isLoading.value = false
    }
  }

  async function updateMemberRole(id, newRole) {
    try {
      const response = await fetch(`/api/crew/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ role: newRole })
      })

      if (!response.ok) throw new Error('Update failed')

      const updated = await response.json()
      const index = members.value.findIndex(m => m.id === id)
      if (index !== -1) {
        members.value[index] = updated
      }
    } catch (e) {
      error.value = e.message
      throw e
    }
  }

  return { members, isLoading, error, fetchCrew, updateMemberRole }
})

Obsługa błędów w actions

Wzorzec try/catch/finally jest standardem w asynchronicznych actions:

async function saveData(data) {
  isLoading.value = true
  error.value = null

  try {
    const result = await apiCall(data)
    // Sukces - aktualizuj state
    items.value.push(result)
    return result
  } catch (e) {
    // Błąd - zapisz komunikat
    error.value = e.message
    throw e // Przekaż błąd do komponentu
  } finally {
    // Zawsze - wyłącz loading
    isLoading.value = false
  }
}

Wywoływanie actions z komponentu

<script setup>
import { onMounted } from 'vue'
import { useCrewStore } from '@/stores/crew'

const crewStore = useCrewStore()

// Wywołanie przy montowaniu
onMounted(() => {
  crewStore.fetchCrew()
})

// Handler z obsługą błędu
async function handleAddMember(member) {
  try {
    await crewStore.addMember(member)
  } catch (e) {
    alert('Error: ' + e.message)
  }
}
</script>
Kod do tej lekcji: App.vue
<script setup>
import { ref, computed } from 'vue'

// Symulacja store załogi z actions
const members = ref([
  { id: 1, name: 'Komandor Nova', role: 'komandor', status: 'active' },
  { id: 2, name: 'Inżynier Atlas', role: 'inżynier', status: 'active' },
  { id: 3, name: 'Naukowiec Darwin', role: 'naukowiec', status: 'resting' }
])
const isLoading = ref(false)
const error = ref(null)
const newName = ref('')
const newRole = ref('inżynier')

// Getters
const activeMembers = computed(() =>
  members.value.filter(m => m.status === 'active')
)
const crewCount = computed(() => members.value.length)

// Actions
async function fetchCrew() {
  isLoading.value = true
  error.value = null
  try {
    await new Promise(r => setTimeout(r, 1000))
    members.value.push({
      id: Date.now(),
      name: 'Dr. Mars ' + Math.floor(Math.random() * 100),
      role: 'naukowiec',
      status: 'active'
    })
  } catch (e) {
    error.value = e.message
  } finally {
    isLoading.value = false
  }
}

function addMember() {
  if (!newName.value.trim()) {
    error.value = 'Imię jest wymagane'
    return
  }
  if (members.value.length >= 8) {
    error.value = 'Osiągnięto maksymalny rozmiar załogi (8)!'
    return
  }
  error.value = null
  members.value.push({
    id: Date.now(),
    name: newName.value,
    role: newRole.value,
    status: 'active'
  })
  newName.value = ''
}

function removeMember(id) {
  members.value = members.value.filter(m => m.id !== id)
}

function toggleStatus(id) {
  const member = members.value.find(m => m.id === id)
  if (member) {
    member.status = member.status === 'active' ? 'resting' : 'active'
  }
}
</script>

<template>
  <div class="nova-lab">
    <h1>NOVA LAB - demo actions</h1>

    <div class="stats">
      <span>Załoga: {{ crewCount }}/8</span>
      <span>Aktywni: {{ activeMembers.length }}</span>
    </div>

    <div class="add-form">
      <input v-model="newName" placeholder="Imię członka załogi..." class="input" />
      <select v-model="newRole" class="input">
        <option value="komandor">Komandor</option>
        <option value="inżynier">Inżynier</option>
        <option value="naukowiec">Naukowiec</option>
      </select>
      <button @click="addMember" class="btn">Dodaj członka</button>
      <button @click="fetchCrew" :disabled="isLoading" class="btn btn-alt">
        {{ isLoading ? 'Ładowanie...' : 'Pobierz z API' }}
      </button>
    </div>

    <div v-if="error" class="error">{{ error }}</div>

    <div class="crew-list">
      <div v-for="member in members" :key="member.id"
        class="crew-card" :class="member.status">
        <div class="crew-info">
          <strong>{{ member.name }}</strong>
          <span class="role">{{ member.role }}</span>
          <span class="status-badge">{{ member.status }}</span>
        </div>
        <div class="crew-actions">
          <button @click="toggleStatus(member.id)" class="btn-sm">
            {{ member.status === 'active' ? 'Odpocznij' : 'Aktywuj' }}
          </button>
          <button @click="removeMember(member.id)" class="btn-sm btn-danger">
            Usuń
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.nova-lab {
  background: #0a0e27;
  color: #00ff88;
  min-height: 100vh;
  padding: 20px;
  font-family: monospace;
}
h1 { color: #00ff88; margin-bottom: 15px; text-align: center; }
.stats { text-align: center; margin-bottom: 15px; color: #00b4d8; }
.stats span { margin: 0 10px; }
.add-form { display: flex; gap: 8px; margin-bottom: 15px; flex-wrap: wrap; max-width: 600px; margin: 0 auto 15px; }
.input {
  background: #0a0e27;
  border: 2px solid #00b4d8;
  color: #00ff88;
  padding: 8px;
  font-family: monospace;
  flex: 1;
  min-width: 120px;
}
.btn {
  background: #00b4d8;
  color: #0a0e27;
  border: none;
  padding: 8px 16px;
  cursor: pointer;
  font-family: monospace;
  font-weight: bold;
}
.btn:hover { background: #00ff88; }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-alt { background: #00ff88; }
.error {
  background: rgba(255, 68, 68, 0.1);
  border: 2px solid #ff4444;
  color: #ff4444;
  padding: 10px;
  margin-bottom: 15px;
  max-width: 600px;
  margin: 0 auto 15px;
}
.crew-list { max-width: 600px; margin: 0 auto; }
.crew-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  border: 2px solid #00ff88;
  background: rgba(0, 255, 136, 0.05);
  flex-wrap: wrap;
  gap: 8px;
}
.crew-card.resting { border-color: #ff9900; opacity: 0.7; }
.crew-info { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.role { color: #00b4d8; }
.status-badge {
  padding: 2px 8px;
  font-size: 0.8em;
  background: rgba(0, 255, 136, 0.2);
  color: #00ff88;
}
.crew-card.resting .status-badge { background: rgba(255, 153, 0, 0.2); color: #ff9900; }
.crew-actions { display: flex; gap: 5px; }
.btn-sm {
  background: #00b4d8;
  color: #0a0e27;
  border: none;
  padding: 4px 10px;
  cursor: pointer;
  font-family: monospace;
  font-size: 0.85em;
}
.btn-danger { background: #ff4444; color: #fff; }
</style>

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Czym są actions w Pinia?

  2. 2. Czy actions w Pinia mogą być asynchroniczne?

To 2 z 3 pytań do tej lekcji. Pozostałe rozwiążesz w grze.

Zadania praktyczne w grze

  • Edytor kodu

    Dodaj async action fetchCrew (try/catch/finally) i action removeMember.

  • Układanie w pionie

    Ułóż wzorzec async action z obsługą błędów:

  • Edytor kodu

    Stwórz addMember z walidacją (max 4) i fetchWithError symulujący błąd API.

  • Klikanie w kolejności

    Ułóż kroki używania store w <script setup>:

  • Układanie w pionie

    Uporządkuj kroki wykonywania async action:

  1. PytanieCzym są actions?
  2. PytanieAsynchroniczne actions
  3. Zadanie z kodemPraktyka: Async actions
  4. Ułóż w kolejnościWzorzec async action
  5. PytanieWywoływanie actions
  6. Zadanie z kodemPraktyka: Error handling w actions
  7. Kliknij w kolejnościUżycie store w komponencie
  8. Ułóż w kolejnościPrzepływ async action

Przydatne artykuły