use-controller
em-use-controller
is a lightweight, flexible HTTP controller hook for React apps that simplifies API calling by abstracting route definitions, authorization, headers, query/path params, and error handling — all in one unified setup.
✨ Features
- ✅ Declarative API calling using controller keys instead of hardcoded URLs.
- 🔐 Built-in auth support (Bearer, custom headers, etc).
- 🔄 Full HTTP method support (
GET
,POST
,PATCH
,DELETE
, etc.). - 🌐 Dynamic path and query param handling.
- 🧪 Centralized error handling and reusable configuration.
- 🪶 Lightweight – No dependencies beyond
axios
. - ⚙️ Works with any backend (especially powerful with RESTful .NET controllers).
🚀 Getting Started
1. Install
npm install em-use-controller
2. Define Your Routes
Create a controller.config.ts file:
import type { ControllerConfig } from 'em-use-controller';
const config: ControllerConfig = {
getSample: "/api/Sample/:id",
updateSample: "/api/Sample/:id",
deleteSample: "/api/Sample/:id",
createSample: "/api/Sample",
uploadSample: "/api/Sample/upload",
securePath: "/api/Sample/secure",
};
export default config;
3. Configure Global Defaults
In your app setup (e.g., App.tsx or main.tsx) or javascript:
import { setControllerDefaults } from 'em-use-controller';
import config from './controller.config.ts';
setControllerDefaults(config, {
baseURL: 'https://localhost:7269',
headers: {
'Content-Type': 'application/json',
},
errorHandler: (error) => {
console.error('Controller Error:', error);
throw error;
},
});
🧩 Usage Example
import { useController } from 'em-use-controller';
const getUser = useController('getUser');
const loadUser = async () => {
const result = await getUser({
method: 'GET',
pathParams: { id: 123 },
auth: {
type: 'bearer',
token: localStorage.getItem('token')!,
},
});
console.log(result.data);
};
🔐 Auth Support
Built-in support for multiple auth modes:
auth: { type: 'none' } // default
auth: { type: 'bearer', token: 'YOUR_JWT_TOKEN' }
auth: {
type: 'custom',
apply: (headers) => {
headers['x-api-key'] = 'custom-value';
},
}
🧠 When to Use use-controller
✅ You want consistent, declarative API calls across your React app.
✅ You work with RESTful APIs (especially ASP.NET Core MVC).
✅ You need dynamic path/query support without boilerplate.
✅ You want to define routes once and reuse them easily.
✅ You need centralized error and auth handling.
💡 Why use-controller is the Best
🧼 No boilerplate: Write less, do more.
🧱 Scalable: Keeps your API calls clean even as your app grows.
🔌 Pluggable: Use any auth system, any backend, any content-type.
⚙️ Customizable: Swap out axios, add global error logic, support file uploads, etc.
🔐 Secure by design: Avoid accidental hardcoded tokens/URLs.
🛠 Advanced Use Cases
✅ Works great with token refresh systems.
✅ Plug into React Query or SWR.
✅ Add file upload support (just pass FormData).
✅ Use with custom Axios instances (e.g., interceptors, retries).
More
Use the demo provided to start testing, easily swap out the backend provided for any comfortable technology. For this, there was already an existing testing backend to use.
https://github.com/Ethern-Myth/use-controller-demo
LICENSE
MIT
Author
Created and Maintained by: Ethern-Myth
Give a like to this project and let's share it and spread it more. Thanks.