USD ($)
$
United States Dollar
Euro Member Countries
India Rupee

Consuming APIs in React/Vue.js with Axios/Fetch

Lesson 22/30 | Study Time: 26 Min

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.

javascript
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

javascript
// 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.

javascript
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.

javascript
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.

javascript
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.

javascript
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.

javascript
const useCart = () => {
const addItem = async (item) => {
await api.post('/cart', item);
};
return { addItem };
};
himanshu singh

himanshu singh

Product Designer
Profile

Class Sessions

1- HTTP Methods and REST Principles 2- Status Codes, Headers, and Request/Response cycles 3- JSON and XML Data Formats for API Payloads 4- Resource Naming Conventions and URI Design Best Practices 5- Statelessness, HATEOAS, and API Versioning Strategies 6- Rate Limiting, Caching, and Idempotency for Scalability 7- FastAPI Setup, Pydantic Models, and Async Endpoint Creation 8- Path/Query Parameters, Request/Response Validation 9- Dependency Injection and Middleware for Authentication/Authorization 10- SQLAlchemy ORM with Async Support for PostgreSQL/MySQL 11- CRUD Operations via API Endpoints with Relationships 12- Database Migrations Using Alembic and Connection Pooling 13- JWT/OAuth2 Implementation with FastAPI Security Utilities 14- File Uploads, Pagination, and Real-Time WebSockets 15- Input Sanitization, CORS, and OWASP Top 10 Defenses 16- Unit/integration testing with Pytest and FastAPI TestClient 17- API Documentation Generation with OpenAPI/Swagger 18- Mocking External Services and Load Testing with Locust 19- Containerization with Docker and Orchestration via Docker Compose 20- Deployment to Cloud Platforms 21- CI/CD Pipelines Using GitHub Actions and Monitoring with Prometheus 22- Consuming APIs in React/Vue.js with Axios/Fetch 23- State Management (Redux/Zustand) for API Data Flows 24- Error Handling, Optimistic Updates, and Frontend Caching Strategies 25- Async Processing with Celery/Redis for Background Tasks 26- Caching Layers (Redis) and Database Query Optimization 27- Microservices Patterns and API Gateways 28- Building a Full-Stack CRUD App with User Auth and File Handling 29- API Analytics, Logging (Structlog), and Error Tracking 30- Code Reviews, Maintainability, and Evolving APIs in Production