A tiny Redux middleware written in TypeScript that turns API calls into plain Redux actions. Instead of wiring axios into every component or thunk, you dispatch a declarative action that describes the request plus the success and failure actions, and the middleware performs the call for you.
- Keeps components free of HTTP logic
- One consistent place for headers, errors and request handling
- Success / failure actions stay explicit and testable
git clone https://github.com/galshir/redux-middleware-core.git
cd redux-middleware-core
npm install
npm run buildDependencies: redux, react-redux, axios, typescript.
Register the middleware when you create the store:
import { createStore, applyMiddleware } from "redux";
import { middleware } from "./src/middleware-redux";
import rootReducer from "./reducers";
const store = createStore(rootReducer, applyMiddleware(middleware));Then build API actions with apiAction:
import { apiAction } from "./src/middleware-redux";
export const fetchUsers = () =>
apiAction({
type: "FETCH_USERS",
url: "https://api.example.com/users",
method: "GET",
onSuccess: (data) => ({ type: "FETCH_USERS_SUCCESS", payload: data }),
onFailure: (error) => ({ type: "FETCH_USERS_FAILURE", payload: { error } }),
});The middleware passes the action on to the next middleware, performs the request with axios (Content-Type: application/json by default, merged with any headers you pass), and dispatches the result of onSuccess or onFailure.
Redux middleware. Forwards every action, and performs the request when the action carries an API descriptor.
Creates an API action. Options:
| Option | Type | Description |
|---|---|---|
type |
string |
Action type, defaults to "API" |
url |
string |
Request URL |
method |
Method |
HTTP method (axios method) |
data |
object |
Request body |
headers |
AxiosRequestHeaders |
Extra request headers |
payload |
object |
Payload attached to the dispatched action |
onSuccess |
(data) => Action |
Action dispatched with the response data |
onFailure |
(error) => Action |
Action dispatched when the request fails |
Returns an API_ERROR action and optionally invokes a callback with the error first.
middleware currently looks for the API descriptor on action.api, while apiAction nests it under metaData.api. The two need to agree before the package can be used as-is.
- Align the action shape between
middlewareandapiAction - Publish an
index.tsentry point and package the build output - Request cancellation and retry support
- Unit tests