January 8, 2025
O. Wolfson
When working with APIs in JavaScript, two popular tools for making HTTP requests are the native fetch function and the third-party library axios. While both are capable of handling HTTP requests, each has unique features that suit different use cases. This article demonstrates their differences through examples using the JSONPlaceholder API.
To follow along, ensure you have:
We will use jsonplaceholder to fetch posts data.
fetchjavascriptimport fetch from "node-fetch";
const fetchPosts = async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log("Posts fetched using fetch:", data);
} catch (error) {
console.error("Error fetching posts with fetch:", error);
}
};
fetchPosts();
fetchfetch is native to JavaScript, requiring no external dependencies.response.json().fetchnode-fetch).fetchaxiosjavascriptimport axios from "axios";
const fetchPostsWithAxios = async () => {
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
console.log("Posts fetched using axios:", response.data);
} catch (error) {
console.error("Error fetching posts with axios:", error.message);
}
};
fetchPostsWithAxios();
axiosfetch.axiosaxiosfetch.fetch and axios| Feature | fetch | axios |
|---|---|---|
| Native to JavaScript | Yes | No (third-party dependency) |
| JSON Parsing | Manual | Automatic |
| Error Handling | Manual | Built-in |
fetchYou’re building a static website that fetches and displays posts without additional error handling or timeout requirements.
axiosYou’re building a dynamic dashboard with multiple API calls, error-handling requirements, and potential scalability needs.
Here are interactive React components to demonstrate both approaches using Next.js 15. Each component fetches data from the JSONPlaceholder API and displays the results.
javascript"use client";
import { useEffect, useState } from "react";
const FetchComponent = () => {
const [posts, setPosts] = useState([]);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState<boolean>(true); // Loading state added
useEffect(() => {
const fetchPosts = async () => {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
setPosts(data);
} catch (err) {
if (err instanceof Error) {
setError(err.message);
} else {
setError("An unknown error occurred");
}
} finally {
setLoading(false); // Stop loading once the request is complete
}
};
fetchPosts();
}, []);
return (
Fetch Demo
Key Features:
Built-in JavaScript function, no external library required.
Manual JSON parsing and error handling needed.
Limited advanced features without custom implementations.
{loading ? (
Loading posts...
) : error ? (
Error: {error}
) : (
{posts.map((post: { id: number; title: string }) => (
{JSON.stringify(post)}
))}
)}
);
};
;
Key Features:
Loading posts...
javascript// pages/axios-demo.js
"use client";
import { useEffect, useState } from "react";
import axios from "axios";
const AxiosComponent = () => {
const [posts, setPosts] = useState([]);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState<boolean>(true); // Loading state added
useEffect(() => {
const fetchPostsWithAxios = async () => {
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
setPosts(response.data);
} catch (err) {
if (err instanceof Error) {
setError(err.message);
} else {
setError("An unknown error occurred");
}
} finally {
setLoading(false); // Stop loading once the request is complete
}
};
fetchPostsWithAxios();
}, []);
return (
<div className="mb-4 p-4 border rounded shadow">
<h2 =>Axios Demo
Key Features:
Automatic JSON parsing—data is ready to use.
Built-in error handling for non-2xx status codes.
Supports advanced features like timeouts and interceptors.
{loading ? (
Loading posts...
) : error ? (
Error: {error}
) : (
{posts.map((post: { id: number; title: string }) => (
{JSON.stringify(post)}
))}
)}
);
};
;
Key Features:
Loading posts...
Both fetch and axios are effective tools for API calls in JavaScript. The React components above illustrate their implementation in a Next.js 15 environment. Depending on your project’s complexity and requirements, choose the tool that best suits your needs.
| Custom implementation required |
| Built-in |
| Syntax | Verbose for advanced use cases | Cleaner and more concise |
| Advanced Features | Limited | Interceptors, cancellation, etc. |