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
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
const { data } = await api.get('/jobs', { params: { city: 'Pune' } });
await api.post('/applications', { jobId });fetch vs Axios
| fetch | Axios | |
|---|---|---|
| Bundled with the browser | yes | no — a dependency |
| JSON parsing | manual res.json() | automatic |
| Rejects on 4xx/5xx | no | yes |
| Interceptors | no | yes |
| Timeout | manual via AbortSignal | timeout option |
| Upload progress | no | yes |
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.
