FrontEND/vue

Pinia + Axios로 API 상태관리 연동하기

mingmingIT 2025. 4. 24. 10:14

Pinia는 단순한 상태관리 라이브러리지만, 비동기 API 호출과 함께 사용하면 강력한 전역 상태 관리 도구로 활용할 수 있습니다.
이번 포스팅에서는 Axios로 API를 호출하고, 그 결과를 Pinia 상태로 관리하는 실전 구조를 소개합니다.


📁 폴더 구조

src/
├── api/
│   └── axiosInstance.js
├── stores/
│   └── usePostStore.js
└── views/
    └── PostListView.vue

🔧 1. Axios 인스턴스 구성

공통 Axios 인스턴스를 만들어 재사용 가능하게 합니다.

// src/api/axiosInstance.js
import axios from 'axios'

const axiosInstance = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com', // 예시용 API
  timeout: 5000
})

export default axiosInstance

🧩 2. Pinia Store에서 Axios 연동

API 호출 로직을 Store 안의 actions에서 처리하면 컴포넌트는 UI에만 집중할 수 있습니다.

// src/stores/usePostStore.js
import { defineStore } from 'pinia'
import axios from '@/api/axiosInstance'

export const usePostStore = defineStore('post', {
  state: () => ({
    posts: [],
    loading: false,
    error: null
  }),

  actions: {
    async fetchPosts() {
      this.loading = true
      this.error = null

      try {
        const response = await axios.get('/posts')
        this.posts = response.data
      } catch (err) {
        this.error = err.message || '알 수 없는 오류가 발생했습니다.'
      } finally {
        this.loading = false
      }
    }
  }
})

🖼️ 3. 컴포넌트에서 Store 사용하기

이제 컴포넌트에서 Store만 불러와서 fetchPosts()를 호출하면 됩니다.

<!-- src/views/PostListView.vue -->
<script setup>
import { onMounted } from 'vue'
import { usePostStore } from '@/stores/usePostStore'

const postStore = usePostStore()

onMounted(() => {
  postStore.fetchPosts()
})
</script>

<template>
  <div class="p-4">
    <h1 class="text-2xl font-bold mb-4">📮 게시글 목록</h1>

    <div v-if="postStore.loading">불러오는 중...</div>
    <div v-else-if="postStore.error" class="text-red-500">{{ postStore.error }}</div>

    <ul v-else>
      <li v-for="post in postStore.posts" :key="post.id" class="mb-2 border-b pb-2">
        <h2 class="font-semibold">{{ post.title }}</h2>
        <p>{{ post.body }}</p>
      </li>
    </ul>
  </div>
</template>

✨ 구조 설명 요약

구성요소 설명
axiosInstance.js Axios 기본 설정을 위한 공통 인스턴스
Pinia Store 상태 저장 및 API 호출 처리
컴포넌트 Store에서 필요한 데이터만 가져와 렌더링

✅ 정리

  • API 호출을 Store의 actions 안에서 관리하면 비즈니스 로직이 분리되어 컴포넌트가 깔끔해집니다.
  • loading, error, data 3가지 상태를 항상 함께 관리하면 **사용자 경험(UX)**이 좋아집니다.
  • 프로젝트가 커질수록 이런 구조는 유지보수에 큰 이점을 줍니다.