swr-resource
v1.0.2
Published
A zero-boilerplate, modern CRUD resource wrapper around SWR for fast React data fetching.
Maintainers
Readme
⚡ swr-resource
A zero-boilerplate, modern resource wrapper around SWR for lightning-fast React data fetching and CRUD operations.
Built for enterprise-scale applications, swr-resource eliminates repetitive API calls, loading state management, and manual cache updates. It keeps your UI synchronized automatically.
✨ Features
- 🚀 Zero Boilerplate – Perform complete CRUD operations with a single hook.
- 🔄 Automatic Cache Sync – UI updates automatically after
create,update, andremoveoperations. - 🔐 Global Configuration – Configure your API base URL and authentication token once.
- 📦 Lightweight – Built on top of the powerful
swrlibrary. - 💙 TypeScript Ready – Fully typed for an excellent developer experience.
- ⚡ Optimized Performance – Leverages SWR's caching and revalidation features.
📦 Installation
Install swr-resource along with its peer dependency, SWR.
npm install swr-resource swror
yarn add swr-resource swror
pnpm add swr-resource swr🛠️ Setup
Wrap your application with the ApiProvider.
This allows you to configure a global API base URL and automatically inject authentication tokens into every request.
// App.tsx
import React from "react";
import { ApiProvider } from "swr-resource";
import Dashboard from "./Dashboard";
export default function App() {
return (
<ApiProvider
baseURL="https://api.yourdomain.com/v1"
getAuthToken={() => localStorage.getItem("access_token")}
>
<Dashboard />
</ApiProvider>
);
}💻 Usage
Once the provider is configured, use the useResource hook anywhere in your application.
import React, { useState } from "react";
import { useResource } from "swr-resource";
interface User {
id: string;
name: string;
email: string;
}
export default function UserManagement() {
const {
data: users,
isLoading,
error,
create,
remove,
} = useResource<User[]>("/users");
const [newName, setNewName] = useState("");
if (isLoading) return <p>Loading users...</p>;
if (error) return <p>Failed to load users.</p>;
const handleAddUser = async () => {
await create({
name: newName,
email: "[email protected]",
});
setNewName("");
};
return (
<div>
<h2>User Management</h2>
<div>
<input
value={newName}
onChange={(e) => setNewName(e.target.value)}
placeholder="Enter user name"
/>
<button onClick={handleAddUser}>
Add User
</button>
</div>
<ul>
{users?.map((user) => (
<li key={user.id}>
{user.name} ({user.email})
<button
onClick={() => remove(user.id)}
>
Delete
</button>
</li>
))}
</ul>
</div>
);
}📚 API Reference
<ApiProvider />
Props
| Prop | Type | Description |
|------|------|-------------|
| baseURL | string | Base URL of your API (e.g. https://api.example.com) |
| getAuthToken | () => string \| null | Function that returns the current Bearer token. It is evaluated before every request. |
useResource(endpoint)
Returns the following object:
| Property | Type | Description |
|----------|------|-------------|
| data | T | Fetched resource data |
| isLoading | boolean | true while the initial request is loading |
| isValidating | boolean | true whenever SWR is revalidating |
| error | Error | Error object if the request fails |
| create(payload) | Promise<any> | Sends a POST request and automatically revalidates the cache |
| update(id, payload) | Promise<any> | Sends a PUT request to endpoint/:id and revalidates |
| remove(id) | Promise<any> | Sends a DELETE request to endpoint/:id and revalidates |
| refresh() | () => void | Manually re-fetches the current resource |
Example
const {
data,
create,
update,
remove,
refresh,
} = useResource("/products");Why swr-resource?
Instead of writing this:
const { data, mutate } = useSWR("/users");
await axios.post("/users", payload);
mutate();Simply write:
const { data, create } = useResource("/users");
await create(payload);No manual cache updates.
No repetitive Axios calls.
Just clean, declarative CRUD.
Requirements
- React 18+
- SWR 2+
- TypeScript (optional but recommended)
License
MIT
