A TypeScript-based utility to generate React
hooks and HTTP methods (GET
, POST
, PUT
, DELETE
) with unified error handling, headers support, response tracking, token refresh, and enhanced developer experience.
This utility provides:
β
React Hooks: useGet
, usePost
, usePut
, useDelete
β
Direct HTTP methods: httpClient.get
, httpClient.post
, httpClient.put
, httpClient.del
β
Cache management with FetchCacheProvider
β
Automatic token refresh with customizable logic
It simplifies working with REST APIs in a type-safe, scalable way with built-in support for authentication and caching.
Initialize the hooks and HTTP client with a base URL and optional configuration, including token refresh logic:
export const {
useGet,
useDelete,
usePost,
usePut,
httpClient,
FetchCacheProvider,
} = createFetchHooks(
"http://localhost:3000/", // API base url
{
accessTokenLocalStorageKey: "accessToken",
callRefreshToken() {
return {
on: [403], // The response code to be tracked to refresh token
body: { refreshToken: localStorage.getItem("refreshToken") || "" }, // refresh token body
endpoint: "/refresh", // The refresh token end point
saveAccessTokenFromResponse: async function (res) {
localStorage.setItem("accessToken", res?.accessToken);
},
};
},
}
);
Wrap your app with FetchCacheProvider
to enable caching:
import { FetchCacheProvider } from "create-fetch-hooks";
function App() {
return (
<FetchCacheProvider>
<YourApp />
</FetchCacheProvider>
);
}
Feature | create-fetch-hooks | Axios | React Query |
---|---|---|---|
Fully typed with generics | β | β | |
React-friendly hooks | β | β | β |
Custom onResponse tracking |
β | β | β |
Optional debounce for useGet |
β | β | |
Unified header injection | β | ||
Minimalistic, no extra deps | β | β | β |
Convert to FormData in POST/PUT |
β | β | |
Works without any context provider | β | β | β |
Token refresh support | β | ||
Cache management with FetchCacheProvider |
β | β | β |
npm i create-fetch-hooks
import { createFetchHooks } from "create-fetch-hooks";
Hook | Return |
---|---|
useGet |
{ data, error, loading, reload } |
usePost |
{ error, loading, postData } |
usePut |
{ error, loading, putData } |
useDelete |
{ error, loading, deleteData } |
π /hooks/api.ts
import { createFetchHooks } from "create-fetch-hooks";
export const {
useGet,
usePost,
usePut,
useDelete,
httpClient,
FetchCacheProvider,
} = createFetchHooks("https://api.example.com", {
staticHeaders: {
"Content-Type": "application/json",
},
accessTokenLocalStorageKey: "accessToken",
callRefreshToken() {
return {
on: [403],
body: { refreshToken: localStorage.getItem("refreshToken") || "" },
endpoint: "/refresh",
saveAccessTokenFromResponse: async (res) => {
localStorage.setItem("accessToken", res?.accessToken);
},
};
},
onResponse(url, endpoint, responseCode) {
if (endpoint === "/me" && responseCode === 401) {
localStorage.removeItem("accessToken");
window.location.href = "/login";
}
},
});
π /pages/UserList.tsx
import { useGet } from "../hooks/api";
interface User {
id: number;
name: string;
}
const UserList = () => {
const { data: users, loading, error, reload } = useGet<User[]>("/users");
if (loading) return <p>Loading...</p>;
if (error) return <p>Error occurred: {error.message}</p>;
return (
<ul>
{users?.map((user) => (
<li key={user.id}>{user.name}</li>
))}
<button onClick={reload}>Reload</button>
</ul>
);
};
export default UserList;
π /App.tsx
import { FetchCacheProvider } from "../hooks/api";
import UserList from "./pages/UserList";
function App() {
return (
<FetchCacheProvider>
<UserList />
</FetchCacheProvider>
);
}
export default App;
All options and return types are strongly typed with TypeScript. Key configuration options include:
staticHeaders
: Static headers applied to all requests.setHeaders
: Function to dynamically generate headers for each request.accessTokenLocalStorageKey
: Key for retrieving access token from localStorage.callRefreshToken
: Configures token refresh logic, including response codes, endpoint, body, and token storage.onResponse
: Callback for handling responses globally.onSuccess
,onError
,onResponseGot
: Callbacks for specific hooks.convertToFormData
,removeIfValueIsNullOrUndefined
: Options for POST/PUT data handling.debounce
,dontRequestIfUrlIncludeNullOrUndefined
: Options for GET requests.
Check the source code and full examples on GitHub for detailed usage.
- π NPM: create-fetch-hooks
- π GitHub: ashrafbinahmad/create-fetch-hooks
If you find this package helpful, please β the repo on GitHub! It really helps! π
MIT