- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array length
- Arrays
- Between braces
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Destructuring
- Else
- Else if
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- Function
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Overriding methods
- Parameters
- Promises
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- Substring
- Template literals
- Tile
- Type conversion
- While loop
JAVASCRIPT
JavaScript Fetch API: Syntax, Usage, and Examples
The JavaScript Fetch API lets you make HTTP requests in a simple, promise-based way. You can use it to fetch data from APIs, send data to servers, and handle network requests efficiently.
How to Use the Fetch API in JavaScript
The Fetch API provides a fetch()
method that returns a Promise.
Basic Syntax
fetch(url, options)
.then(response => response.json()) // Convert response to JSON
.then(data => console.log(data)) // Handle the data
.catch(error => console.error("Error fetching data:", error)); // Handle errors
url
is the endpoint you want to fetch data from.options
(optional) lets you specify the request type (GET, POST, etc.) and additional settings..then(response => response.json())
converts the response to JSON format..catch(error => console.error())
logs errors if the request fails.
When to Use the Fetch API in JavaScript
Use the Fetch API when you need to interact with external data sources.
- Fetch data from an API, like weather reports or user details.
- Send form data to a server with a POST request.
- Load large datasets in the background to keep a page responsive.
Examples of Fetch API in JavaScript
Fetching Data from an API with GET
You can use a GET request to retrieve data from an API.
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json())
.then(user => console.log("User:", user))
.catch(error => console.error("Error fetching user data:", error));
Sending Data with a POST Request
A POST request sends data to an API.
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "New Post",
body: "This is a new post.",
userId: 1
})
})
.then(response => response.json())
.then(data => console.log("Post created:", data))
.catch(error => console.error("Error posting data:", error));
Handling Errors
Handling errors prevents unexpected behavior.
fetch("https://invalid-api.com/data")
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error("Fetch error:", error.message));
If the API is unavailable or returns a 404/500 error, the catch()
block handles it.
Learn More About the Fetch API in JavaScript
Using async and await for Cleaner Code
You can replace .then()
with async
and await
to make code easier to read.
async function fetchData() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
let data = await response.json();
console.log("Post:", data);
} catch (error) {
console.error("Error fetching post:", error);
}
}
fetchData();
Fetching Multiple Requests at Once
You can fetch multiple APIs at the same time with Promise.all()
.
Promise.all([
fetch("https://jsonplaceholder.typicode.com/users/1").then(res => res.json()),
fetch("https://jsonplaceholder.typicode.com/posts/1").then(res => res.json())
])
.then(([user, post]) => {
console.log("User:", user);
console.log("Post:", post);
})
.catch(error => console.error("Error fetching data:", error));
Fetching API Data in JavaScript React
In React, use the Fetch API inside useEffect()
to fetch data when a component loads.
import { useState, useEffect } from "react";
function App() {
const [data, setData] = useState(null);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error("Error fetching data:", error));
}, []);
return (
<div>
{data ? <h1>{data.title}</h1> : <p>Loading...</p>}
</div>
);
}
export default App;
Fetch API vs. XMLHttpRequest
The Fetch API replaces XMLHttpRequest
(XHR) because:
- It uses Promises, which makes code more readable.
- It has built-in JSON handling with
response.json()
. - It supports streaming and better request customization.
Caching API Responses
To avoid unnecessary API calls, store responses in localStorage
.
async function fetchWithCache(url) {
let cached = localStorage.getItem(url);
if (cached) {
return JSON.parse(cached);
}
let response = await fetch(url);
let data = await response.json();
localStorage.setItem(url, JSON.stringify(data));
return data;
}
fetchWithCache("https://jsonplaceholder.typicode.com/posts/1")
.then(data => console.log("Fetched data:", data))
.catch(error => console.error("Fetch error:", error));
Fetching Large Data Sets with Pagination
Instead of loading all data at once, use pagination to fetch small chunks.
async function fetchPaginatedData(page) {
let response = await fetch(`https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=5`);
let data = await response.json();
console.log(`Page ${page} data:`, data);
}
fetchPaginatedData(1);
fetchPaginatedData(2);
The JavaScript Fetch API is a powerful tool for making HTTP requests. Using async/await, Promise.all(), and caching techniques, you can optimize your requests and build responsive applications.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.