@benco112/use-req
v1.0.1
Published
Simple and lightweight fetch hook by benco112
Downloads
175
Readme
use-req
Simple and lightweight React hook for making API requests with built-in loading, error, and data state.
Features
- Lightweight and dependency-free
- Built for React Hooks (
>=16.8) - Simple request interface
- Supports custom methods, headers, and body
- Exposes request state in a clean API
Installation
npm install @benco112/use-reqQuick Start
import useReq from "@benco112/use-req";
function UsersList() {
const { data, loading, error, request } = useReq("https://api.example.com");
const loadUsers = async () => {
await request("/users");
};
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return (
<div>
<button onClick={loadUsers}>Load users</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}API
useReq(baseUrl)
Creates a request client scoped to a base URL.
Parameters
baseUrl: string— Base URL for all requests.
Returns
data: any— Last successful response data.loading: boolean— Request state.error: string | null— Error message from the last failed request.request(endpoint, options?)— Function to execute a request.
request(endpoint, options?)
endpoint: string— Path appended tobaseUrl.options.method?: string— HTTP method (default:GET).options.headers?: Record<string, string>— Additional request headers.options.body?: unknown— Request body. It is JSON-stringified when provided.
Example: POST Request
await request("/users", {
method: "POST",
body: { name: "Ben" },
headers: {
Authorization: "Bearer <token>",
},
});Build
npm run buildLicense
MIT
