Lesson 37/100

Tutorials React.js Tutorial

Axios — Complete Guide

Axios — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of React.js Tutorial on Toolliyo Academy.

On this page

React.js Tutorial · Lesson 37 of 100

Axios

Beginner ✓IntermediateAdvancedProfessional

Intermediate · 2 — Build apps · ~14 min read · Module 4: Routing & Data

Introduction

You know the basics now. Here we use Axios in real app situations — forms, pages, and data. Still plain language, just a bit more depth. Axios is an HTTP client library. It automatically parses JSON, has interceptors for auth headers, and throws on 4xx/5xx status codes. Teams use one axios instance with baseURL and auth so every API call does not repeat the same setup.

Routing is how a single React app feels like many pages. Users expect URLs like /cart and /checkout — Router makes that work.

When will you use this?

Add routing when your app has more than one screen and URLs should be bookmarkable.

  • Multi-page apps like dashboards use React Router — /settings, /profile, /orders.
  • E-commerce sites route /product/123 to a product detail component.

Real-world: HDFC API client with interceptors

Banking SPA uses axios instance with base URL, JWT injection, and global 401 handler that redirects to login.

Production-style code

import axios from 'axios';

export const bankingApi = axios.create({
  baseURL: 'https://api.hdfc.example/v1',
  timeout: 15000
});

bankingApi.interceptors.request.use(config => {
  const token = sessionStorage.getItem('accessToken');
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

bankingApi.interceptors.response.use(
  res => res,
  err => {
    if (err.response?.status === 401) window.location.href = '/login';
    return Promise.reject(err);
  }
);

What happens in production: One configured client serves accounts, transfers, and cards — DRY auth and error handling across 40+ endpoints.

Lesson example (start here)

Copy this smaller example first. Once it works, compare it with the real-world code above.

import axios from 'axios';

const api = axios.create({ baseURL: '/api' });

api.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

const { data } = await api.get('/users');

Line-by-line walkthrough

CodeWhat it means
import axios from 'axios';Imports code from React or another file so you can use it here.
const api = axios.create({ baseURL: '/api' });Calls an API to load or save data from a server.
api.interceptors.request.use(config => {Defines a function — often a component or event handler.
const token = localStorage.getItem('token');Part of the Axios example — read it together with the lines before and after.
if (token) config.headers.Authorization = `Bearer ${token}`;Part of the Axios example — read it together with the lines before and after.
return config;Sends UI or a value back to whoever called this function.
});Closes a block started by { or ( above.
const { data } = await api.get('/users');Part of the Axios example — read it together with the lines before and after.

How it works (big picture)

  • create sets base URL once.
  • Interceptor runs before each request.
  • await api.get throws if server returns error status.

Do this on your computer

  1. npm install axios
  2. Create api.js with axios.create.
  3. Import api in components instead of raw fetch.
  4. Read the real-world section and name which part of the app uses this topic.
  5. Run the example locally and confirm the same behavior in the browser.
  6. Change one value in the example (text, initial state, or URL) and predict what will happen before you save.

Experiments — try changing this

  • Change text or labels in the example and save — watch the browser update.
  • Break the code on purpose (remove a bracket), read the error message, then fix it.
  • Open React DevTools (browser extension) while running Axios and inspect component props/state.

Remember

One shared axios instance per app. Interceptors for auth and errors. async/await with try/catch.

Common questions

Does axios work in Node?

Yes — same API for React and Express backends.

How long should I spend on Axios?

Until you can explain it in your own words and run the example without looking at the answer. Beginners often need 30–60 minutes per new hook or routing topic; setup lessons may take one afternoon.

What if I get stuck on Axios?

Re-read the line-by-line walkthrough, check the browser console for red errors, and compare your code character-by-character with the example. Search the exact error text — someone else had it too.

Where is Axios used in real jobs?

See the real-world section above — the same pattern appears in LMS, banking, e-commerce, and SaaS products. Interviewers ask you to explain it using one concrete example from your project or this lesson.

Interview prep for this lesson

Practice these questions aloud after reading—each links to a full structured answer.

Mid PDF Detailed
Mock axios:?
Short answer: import axios from 'axios'; jest.mock('axios'); axios.get.mockResolvedValue({ data: 'mock data' }); Example code import axios from 'axios'; jest.mock('axios'); axios.get.mockResolvedValue({ data: 'mock data'…
Mid PDF Detailed
Mock axios: import axios from 'axios'; jest.mock('axios');?
Short answer: xios.get.mockResolvedValue({ data: 'mock data' }); xios.get.mockResolvedValue({ data: 'mock data' }); xios.get.mockResolvedValue({ data: 'mock data' }); xios.get.mockResolvedValue({ data: 'mock data' }); Re…
Mid PDF Detailed
React Developer Tools:?
Short answer: Use the Profiler tab to measure the render times and identify slow components. Check for unnecessary re-renders and optimize with React.memo or shouldComponentUpdate. Real-world example (ShopNest) ShopNest’…
Mid PDF Detailed
Choose a Testing Library: Use libraries like Jest (test runner) and React Testing?
Short answer: Library (for testing React components). Real-world example (ShopNest) ShopNest’s storefront is React: components for ProductCard, CartDrawer, and CheckoutForm, with hooks for local UI state. Say this in the…
Mid PDF Detailed
Only call hooks at the top level?
Short answer: (Don’t call hooks inside loops, conditions, or nested functions.) Real-world example (ShopNest) ShopNest’s cart icon uses useState for count and useEffect to load the cart once on mount. Say this in the int…
Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

React.js Tutorial
Course syllabus

React.js Tutorial

Module 1: React Basics & Setup
Module 2: Props, Events & Lists
Module 3: Forms & Hooks
Module 4: Routing & Data
Module 5: State & Authentication
Module 6: Architecture & React 19
Module 7: Performance
Module 8: Full-Stack & Real-Time
Module 9: Testing & Deployment
Module 10: ShopCart Projects
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details