DEV Community

Ethern Myth
Ethern Myth

Posted on

1

Simplify Your API Calls in React with em-use-controller

Sick of writing the same fetch or axios boilerplate over and over? πŸ’€

Meet em-use-controller – a tiny but powerful utility for React, and supported for other SPAs that turns your REST API routes into declarative, type-safe controller functions.

const getUser = useController('getUser');

const result = await getUser({
  method: 'GET',
  pathParams: { id: 123 },
  auth: { type: 'bearer', token },
});
Enter fullscreen mode Exit fullscreen mode

🎯 No more:

  • Hardcoded URLs

  • Manual query string building

  • Duplicated headers/auth logic

  • Messy error handling

πŸš€ How it Works
Define your routes once in a config file:

export default {
  getUser: '/api/users/:id',
  updateUser: '/api/users/:id',
};
Enter fullscreen mode Exit fullscreen mode

Set global defaults for headers, baseURL, and error handling:

setControllerDefaults(config, {
  baseURL: 'https://api.myapp.dev',
  headers: { 'Content-Type': 'application/json' },
  errorHandler: (e) => console.error('API Error', e),
});
Enter fullscreen mode Exit fullscreen mode

Call any endpoint with one-liners using useController.

πŸ›  Features

βœ… Works with all HTTP methods

βœ… Handles path + query params

βœ… Supports Bearer & custom auth

βœ… Built-in global error handling

βœ… Swappable axios instance

βœ… Upload files with FormData

🧠 Ideal For:

  • Frontend devs (React, other SPAs, tested on react based) using RESTful APIs (especially .NET/Java/Spring/Node)

  • Anyone who hates repeated boilerplate

  • Teams that want cleaner, safer API usage

πŸ“¦ Try it Out

npm install em-use-controller
Enter fullscreen mode Exit fullscreen mode

And view on npm

Finally grab the demo on https://github.com/Ethern-Myth/use-controller-demo

All the best! πŸ‘

Redis image

Short-term memory for faster
AI agents

AI agents struggle with latency and context switching. Redis fixes it with a fast, in-memory layer for short-term contextβ€”plus native support for vectors and semi-structured data to keep real-time workflows on track.

Start building

Top comments (0)

Sentry image

Make it make sense

Only get the information you need to fix your code that’s broken with Sentry.

Start debugging β†’

πŸ‘‹ Kindness is contagious

Dive into this thoughtful piece, beloved in the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A sincere "thank you" can brighten someone's dayβ€”leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay