🔰 A redux middleware for handling HTTP requests
It's based on plain old XHR, though not as fancy as fetch, it simply does the job and there's no need for extra dependencies.
npm install redux-req
import { ACTION_TYPE } from 'redux-request';
// dispatch an API request
dispatch({
type: ACTION_TYPE,
resourceName: 'users'
url: '/api/users',
method: 'GET',
requestType: 'REQUEST_API',
receiveType: 'RECEIVE_API'
});
once a request is dispatched, the middleware will dispatch an action of the specified request type, you can make a reducer to handle this action, for instance, update the loading state for the resource.
when the request is completed, the middleware will dispatch an event of the specified receive type, similarly, a reducer can be used to handle the response, with a result of either failure or success.
To dispatch a request middleware aware action, the action should have the following properties:
prop | type | description |
---|---|---|
type | string | required should be the type imported (ACTION_TYPE) from the middleware |
resourceName | string | the name of the resource for which you want to send a request, this is necessary for reducers to identify the request |
url | string | the url of the resource |
method | string | the method of the request |
payload | any | the request payload |
beforeSend | function | a function passed with the XHR object, so that some extra work can be done before sending the request |
To simplify the creation of reducer that can interpret the actions emitted by the middleware, a reducer enhancer is also delivered with the package, here's an example:
import { enhanceReducer } from 'redux-req';
const enhanced = enhanceReducer(a_reducer);
then the state will be injected with the following properties according to the request result.
{
isFetching: boolean,
error: any // payload from the failed request, null if there's no error
}
MIT