Fetch Wrapper
This snippet implements a reusable fetch wrapper to simplify API calls.
This snippet demonstrates how to create a fetch wrapper that handles API requests, manages errors, and simplifies response parsing. This makes it easier to work with REST APIs and reduces boilerplate code.
How It Works
A fetch wrapper abstracts the fetch
API to:
- Automatically parse JSON responses.
- Handle request errors in a centralized way.
- Provide an easy-to-use interface for making API calls.
main.ts
async function fetchWrapper<T>(url: string, options: RequestInit = {}): Promise<T> {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Fetch error:", error);
throw error;
}
}
test.ts
async function getUserData() {
try {
const user = await fetchWrapper<{ name: string; email: string }>("https://api.example.com/user");
console.log(user);
} catch (error) {
console.log("Failed to fetch user data");
}
}
When to Use a Fetch Wrapper
- Consistent API handling: Standardizes API requests and error handling.
- Reduced boilerplate: Eliminates repetitive fetch calls in multiple places.
- Improved readability: Makes API interactions cleaner and easier to understand.