Skip to content

API Calls in Vue

Fetch remote data from event handlers, watchers, or composables — not during render. This lesson covers practical patterns, syntax, and mistakes to avoid.

Calling APIs from Vue

Fetch remote data from event handlers, watchers, or composables — not during render.

Expose loading/error refs from a useFetch-style composable.

async function loadUsers() {
  loading.value = true
  try {
    users.value = await (await fetch('/api/users')).json()
  } finally {
    loading.value = false
  }
}

Manual fetch with loading flag.

Where to Put It

composables, Pinia actions, route-level loaders (Nuxt)
  • Handle loading and errors.
  • Keep composables tested.
  • Prefer TypeScript when you can.
  • Measure before optimizing.

API Calls in Vue Cheatsheet

Quick reference for patterns covered in this lesson.

Item Example Purpose
fetch GET Read
POST create Write
AbortController cancel Races
env VITE_API Base
auth headers Tokens
ok check status Errors

Race Safety

Abort or ignore stale responses when params change quickly.

Common Mistakes

  • Fetching in template expressions.
  • Ignoring non-OK HTTP statuses.

Key Takeaways

  • API Calls in Vue shows up often in Vue apps.
  • Practice with a demo.
  • Prefer clear APIs.
  • Read official docs for edge cases.

Pro Tip

Check response.ok — fetch only rejects on network failure.