Built and signed on GitHub ActionsBuilt and signed on GitHub Actions
A library of hooks for integrating @pretch/core with Preact, designed to simplify the use of fetch and enhance its functionality with customizable behavior.
@pretch/preact
An implementation of @pretch/core for preact. These hooks create a custom
fetch function with optional enhancements to track request status. useFetch
will automatically fetch data when the component is mounted, while useLazyFetch
will fetch when manually triggered.
Features
- Compatible with all JavaScript runtimes (Node.js, Bun, Deno) and browser environments
- Type-safe response handling
- Request enhancement capabilities
- Automatic and manual fetching modes
- Built-in loading and error states
- Support for request middleware
Automatic Fetching
import { useFetch } from "@pretch/preact"; import { useState, useEffect } from "preact/hooks"; const randomNumber = () => Math.floor(Math.random() * 10) + 1; type User = { name: string; username: string; email: string; }; function RandomUser() { const [userId, setUserId] = useState(randomNumber()); const { data, loading, error, refetch } = useFetch<User>(`https://jsonplaceholder.typicode.com/users/${userId}`); useEffect(() => { refetch({newUrl:`https://jsonplaceholder.typicode.com/users/${userId}`}); }, [userId]); const handleClick= () => { setUserId(randomNumber())}; if (loading) return <div>Loading...</div> if (error) return <div>Error while fetching ...</div> return ( <div> <p> Username: {data?.username}<br/> Name: {data?.name}<br/> Email: {data?.email} </p> <button onClick={handleClick}>Get random user</button> </div> ); }
Manual Fetching
import { useLazyFetch } from "@pretch/preact"; import { useState } from "preact/hooks"; function UpdateTodo(){ const [completed,setCompleted] = useState(false); const {data, fetchData, error, loading} = useLazyFetch({url:"https://jsonplaceholder.typicode.com/todos/1"}); const handleClick = () => { setCompleted(c => !c); fetchData({ newOptions:{ method: "PUT", body: JSON.stringify({completed}) } }); }; return ( <div> <span>Task to be done</span> <button onClick={handleClick} disabled={loading}> {completed ? "Complete" : "Not complete"} </button> </div> ); }
Query-based Fetching
import { useQuery } from "@pretch/preact"; type User = {name: string}; function UserManager() { const query = useQuery<User>("https://api.example.com"); const handleGetUser = async (id: string) => { const { data, loading, error } = await query.get(`/users/${id}`); if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return <div>User: {data?.name}</div>; }; const handleCreateUser = async (userData: User) => { const { data } = await query.post<User>("/users", { body: JSON.stringify(userData) }); // Handle the response }; return <div></div>; }
Advanced Usage
Using Middleware
import { useLazyFetch } from '@pretch/preact'; import { applyMiddleware, authorization, retry } from '@pretch/core/middleware'; function SecureComponent() { const { data } = useLazyFetch({ url: "https://api.example.com/secure", enhancer: applyMiddleware( authorization('your-token', 'bearer'), retry({ maxRetries: 3 }) ), }); return <div>render data: {JSON.stringify(data)}</div>; }
Custom Enhancers
import { useFetch } from '@pretch/preact'; import type { Enhancer, Handler } from '@pretch/core'; const loggingEnhancer: Enhancer = (handler: Handler) => { return async (request: Request) => { console.log('Request:', request.url); const response = await handler(request); console.log('Response:', response.status); return response; }; }; function LoggedComponent() { const { data } = useFetch('https://api.example.com', { enhancer: loggingEnhancer }); return <div>render data: {JSON.stringify(data)}</div>; }
API Reference
The package exports three main hooks:
useFetch
Creates a fetch hook that automatically executes on component mount. useFetch
useLazyFetch
Creates a fetch hook that only executes when manually triggered. useLazyFetch
useQuery
Creates a set of HTTP method functions (GET, POST, PUT, etc.) with status tracking. useQuery
Add Package
deno add jsr:@pretch/preact
Import symbol
import * as preact from "@pretch/preact";
Import directly with a jsr specifier
import * as preact from "jsr:@pretch/preact";
Add Package
pnpm i jsr:@pretch/preact
pnpm dlx jsr add @pretch/preact
Import symbol
import * as preact from "@pretch/preact";
Add Package
yarn add jsr:@pretch/preact
yarn dlx jsr add @pretch/preact
Import symbol
import * as preact from "@pretch/preact";
Add Package
vlt install jsr:@pretch/preact
Import symbol
import * as preact from "@pretch/preact";
Add Package
npx jsr add @pretch/preact
Import symbol
import * as preact from "@pretch/preact";
Add Package
bunx jsr add @pretch/preact
Import symbol
import * as preact from "@pretch/preact";