0.1.4 • Published 7 years ago

redux-simple-request v0.1.4

Weekly downloads
3
License
MIT
Repository
github
Last release
7 years ago

Redux Simple Request

Middleware for Redux to manage requests.

Works in the server as in the browser.

Install

npm install redux-simple-request

Add to Redux Store

// ...
import createApiMiddleware from 'redux-simple-request';

// ...

const apiMiddleware = createApiMiddleware();

export default createStore(
  reducer,
  applyMiddleware(apiMiddleware)
);
  • Import the creator: import createApiMiddleware from 'redux-simple-request';.
  • Create middleware: const apiMiddleware = createApiMiddleware();. Options can be passed. Check Advanced.
  • Add to Store: applyMiddleware(apiMiddleware).

Usage

The most simple usage with Action Creators.

import { API } from 'redux-simple-request';

const addUsers = (users) => ({
  type: 'addUsers',
  data: users,
});

const fetchUsers = () => ({
  type: API,
  url: 'www.my-url.com/users',
  onSuccess: (users, dispatch) => {
    return dispatch(addUsers(users));
  }
});

This example will make a request to www.my-url.com/users.

Then it will dispatch the addUsers action with the response data.

Action Properties

PropertyMandatory?TypeDescription
typeYesstringYou have to use the API constant that you import from the package
urlYesstringJust give it the url where you want to make your request
methodNostringHTTP Method for the request. Default GET
dataNoobjectData that needs to be sent with the request
headersNoobjectHeaders for the request
onSuccessNofunctionThis function will be called if the request is successful. onSuccess(data, dispatch, getState). Parameters passed are the response data, dispatcher and getState
onErrorNofunctionThis function will be called if the request is not successful. onError(error, dispatch, getState). Parameters passed are the error, dispatcher and getState
onProgressNofunctionThis function will be called before making the request. onProgress(action, dispatch, getState). Parameters passed are the action, dispatcher and getState

Plus all the additional properties that can be used with Request

Advanced

createApiMiddleware() expects an options object.

PropertyMandatory?TypeDescription
beforeRequestNofunctionThis function will be called for every request. Before the onProgress. beforeRequest(action, dispatch, getState). Parameters are the action, dispatcher and getState

Use cases

  • Add the base url to action.url.
  • Add specific headers or query params to url when user is logged in.