OFetch - A Better Fetch API
OFetch is a lightweight and modern library for making HTTP requests, designed as an improved alternative to the native fetch API. It offers a simpler syntax, better error handling, and advanced features like request cancellation, interceptors, and automatic JSON data handling.
📦 Installation
Section titled “📦 Installation”Install ofetch via npm or yarn:
npm install ofetch# oryarn add ofetch🔧 Basic Usage
Section titled “🔧 Basic Usage”1. GET Request
Section titled “1. GET Request”import { ofetch } from "ofetch";const data = await ofetch("https://api.example.com/users");console.log(data);2. POST Request
Section titled “2. POST Request”const newUser = await ofetch("https://api.example.com/users", { method: "POST", body: { name: "Alice", age: 30 },});console.log(newUser);✨ Advanced Features
Section titled “✨ Advanced Features”Error Handling
Section titled “Error Handling”try { const data = await ofetch("https://api.example.com/unknown");} catch (error) { console.error("Error:", error);}Interceptors
Section titled “Interceptors”const client = ofetch.create({ onRequest({ options }) { options.headers = { ...options.headers, Authorization: "Bearer token" }; },});const data = await client("https://api.example.com/protected");Request Cancellation
Section titled “Request Cancellation”const controller = new AbortController();const promise = ofetch("https://api.example.com/long-request", { signal: controller.signal,});// Cancel the request after 1 secondsetTimeout(() => controller.abort(), 1000);📚 Best Practices
Section titled “📚 Best Practices”- Reuse Instances: Create configured instances to avoid repeating options.
- Handle Errors: Use
try/catchto capture HTTP errors. - Optimize Requests: Use interceptors to add headers or logs.
📖 Official Documentation
Section titled “📖 Official Documentation”For more details, check out the OFetch official documentation.