MyInternships.in

Data Fetching & APIs

React Axios Tutorial

Axios is an HTTP client that adds conveniences over fetch: automatic JSON parsing, HTTP error statuses that reject, request and response interceptors, timeouts and per-instance base URLs.


What is Axios Tutorial in React?

Axios is an HTTP client that adds conveniences over fetch: automatic JSON parsing, HTTP error statuses that reject, request and response interceptors, timeouts and per-instance base URLs.

Why Axios Tutorial matters

On a real project the interceptor is the deciding feature — one place to attach the auth token to every request and to handle a 401 by refreshing or logging the user out.

Axios Tutorial example

A configured instance with interceptors
JavaScript
import axios from 'axios';

export const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000,
});

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

api.interceptors.response.use(
  res => res,
  err => {
    if (err.response?.status === 401) logout();
    return Promise.reject(err);
  }
);

Using it in a component

JSX
const { data } = await api.get('/jobs', { params: { city: 'Pune' } });
await api.post('/applications', { jobId });

fetch vs Axios

fetchAxios
Bundled with the browseryesno — a dependency
JSON parsingmanual res.json()automatic
Rejects on 4xx/5xxnoyes
Interceptorsnoyes
Timeoutmanual via AbortSignaltimeout option
Upload progressnoyes

Common mistakes with Axios Tutorial

  • Creating a new Axios instance inside a component, which rebuilds interceptors on every render.
  • Reading err.message instead of err.response.data for the server’s error body.

React Axios Tutorial— Interview Questions & FAQs

Should I use fetch or Axios?+

fetch is fine for a handful of simple calls with no dependency cost. Choose Axios once you need interceptors for auth, consistent error handling, timeouts or upload progress.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships