@alyvro/api-hooks
v0.1.1
Published
Lightweight React hooks for API integration (Next.js/Node.js friendly).
Maintainers
Readme
@alyvro/api-hooks
Lightweight React hooks for API integration (Next.js/Node.js friendly).
Built by Alyvro → alyvro.com
✨ Features
- 🔗
useApi– Fetch data with caching, loading & error states - 🚀
useMutation– Handle POST/PUT/DELETE with optimistic updates - ♻️
refetch&invalidate– Control cached queries - 📜 Pagination & infinite scroll support
- ⚡ Works perfectly with Next.js & Node.js APIs
📦 Installation
npm install @alyvro/api-hooks
# or
pnpm add @alyvro/api-hooks
# or
yarn add @alyvro/api-hooks🔧 Setup
Wrap your app with the ApiContext.Provider to set a base URL and token handler.
import { ApiContext } from "@alyvro/api-hooks";
function MyApp({ Component, pageProps }) {
return (
<ApiContext.Provider
value={{
baseURL: "/api",
getToken: () => localStorage.getItem("token"),
}}
>
<Component {...pageProps} />
</ApiContext.Provider>
);
}
export default MyApp;🛠 Usage
1. Fetching Data (useApi)
import { useApi } from "@alyvro/api-hooks";
function Profile() {
const { data, loading, error, refetch } = useApi("/user/me");
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h1>{data.name}</h1>
<button onClick={refetch}>Refetch</button>
</div>
);
}2. Mutations (useMutation)
import { useMutation } from "@alyvro/api-hooks";
function UpdateUser() {
const { mutate, loading } = useMutation("/user/update", "PUT", {
optimisticKey: "/user/me",
});
return (
<button
onClick={() => mutate({ name: "Nima" }, { name: "Nima (optimistic)" })}
disabled={loading}
>
Update
</button>
);
}3. Pagination (usePaginatedApi)
import { usePaginatedApi } from "@alyvro/api-hooks";
function UsersList() {
const { data, loading } = usePaginatedApi("/users", 1, 10);
if (loading) return <p>Loading...</p>;
return (
<ul>
{data?.map((u) => (
<li key={u.id}>{u.name}</li>
))}
</ul>
);
}📝 License
MIT © Alyvro
