Skip to content

NPM package to generate React hooks and HTTP methods (GET, POST, PUT, DELETE) with unified error handling, headers support, response tracking, and enhanced developer experience. πŸ€— Download it from NPM, and collaborate

License

Notifications You must be signed in to change notification settings

ashrafbinahmad/create-fetch-hooks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🎞 createFetchHooks – Your Custom API Hook Factory

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.


✨ What is this?

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.


πŸš€ Quick Setup

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>
  );
}

πŸ’‘ Why use this over other libraries?

Feature create-fetch-hooks Axios React Query
Fully typed with generics βœ… ⚠️ βœ…
React-friendly hooks βœ… ❌ βœ…
Custom onResponse tracking βœ… ❌ ❌
Optional debounce for useGet βœ… ❌ ⚠️ Plugin
Unified header injection βœ… ⚠️ ⚠️
Minimalistic, no extra deps βœ… ❌ ❌
Convert to FormData in POST/PUT βœ… ❌ ⚠️ Manual
Works without any context provider βœ… ❌ ❌
Token refresh support βœ… ⚠️ ⚠️ Manual
Cache management with FetchCacheProvider βœ… ❌ βœ…

πŸ“¦ Installation

npm i create-fetch-hooks

πŸ”— Importing

import { createFetchHooks } from "create-fetch-hooks";

πŸ§™β€β™‚οΈ Hook Return Types

Hook Return
useGet { data, error, loading, reload }
usePost { error, loading, postData }
usePut { error, loading, putData }
useDelete { error, loading, deleteData }

🌍 Real-World Usage Example

πŸ“ /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;

πŸ“œ Docs

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.


πŸ“Œ Links

If you find this package helpful, please ⭐ the repo on GitHub! It really helps! πŸ™


πŸ“œ License

MIT

About

NPM package to generate React hooks and HTTP methods (GET, POST, PUT, DELETE) with unified error handling, headers support, response tracking, and enhanced developer experience. πŸ€— Download it from NPM, and collaborate

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published