Consuming APIs in React or Vue.js using Axios or the Fetch API is a common practice for building dynamic, data-driven front-end applications. These tools allow client-side applications to communicate with backend services by sending HTTP requests and handling responses asynchronously.
By integrating API calls into component lifecycles or state management systems, front-end frameworks can display real-time data, handle user interactions, and manage application state efficiently.
Axios vs Fetch Overview
Axios and Fetch serve as primary tools for HTTP requests in modern JavaScript frameworks, each with distinct strengths. Axios is a promise-based library offering automatic JSON parsing, interceptors, and cancellation, ideal for complex apps. Fetch, a native browser API, provides simplicity and no external dependencies but requires manual JSON handling and error checks.

Choose Axios for feature-rich apps and Fetch for lightweight, native solutions.
Setup in React and Vue.js
Start by installing Axios via npm for both frameworks, then configure instances for reusability.
React Setup: Import Axios directly or create a custom instance in a utils file.
import axios from 'axios';
const api = axios.create({ baseURL: 'https://api.example.com' });Use in components with hooks like useEffect.
Vue.js Setup: Register Axios globally or use Composition API imports
// main.js (Vue 3)
import { createApp } from 'vue';
import axios from 'axios';
const app = createApp(App);
app.config.globalProperties.$axios = axios;For Composition API, import per composable.
Fetch requires no setup, as it's browser-native. Always set base URLs to avoid repetition.
Basic API Consumption Examples
Perform CRUD operations with clear, async patterns in both frameworks.
GET Request in React (Axios)
Two lines: Fetch users on mount, manage loading state.
import { useState, useEffect } from 'react';
const [users, setUsers] = useState([]);
useEffect(() => {
api.get('/users').then(res => setUsers(res.data));
}, []);Display with conditional rendering.
POST Request in Vue.js (Fetch)
Two lines: Submit form data, handle response.
const submitUser = async (formData) => {
const response = await fetch('/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
});
if (!response.ok) throw new Error('Failed');
return response.json();
};Bind to form @submit.
1. Use async/await for readability over .then chains.
2. Always check response.ok for Fetch to catch 4xx/5xx errors.
3. Log requests in development for debugging.
Advanced Techniques and Best Practices
Elevate your code with interceptors, hooks, and error strategies for production readiness.
Interceptors (Axios): Centralize auth tokens and logging.
api.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${token}`;
return config;
});Handles global errors too.
Custom Hooks/Composables
1. React: useAxios hook manages loading/error states.
function useAxios(url) {
const [data, setData] = useState();
const [loading, setLoading] = useState(true);
useEffect(() => {
api.get(url).then(setData).finally(() => setLoading(false));
}, [url]);
return { data, loading };
}Vue: Similar in setup() with ref().
Error Handling
1. Wrap in try-catch for async calls.
2. Display user-friendly messages (e.g., "Network error, retry?").
3. Retry logic: Use exponential backoff.
Security and Performance
1. Avoid exposing API keys in frontend; use proxies.
2. Implement AbortController/Fetch for cancellation on unmount.
3. Cache with React Query or Vue Query for repeated calls.
Real-World Integration
In full-stack apps, consume your course-built APIs like user auth or product catalogs.
React Example (Dashboard):
Fetch and post updates with optimistic UI.
1. Loading spinner during requests.
2. Error toast notifications.
Vue Example (E-commerce)
Composable for cart API.
const useCart = () => {
const addItem = async (item) => {
await api.post('/cart', item);
};
return { addItem };
};