redux-restapi
v0.3.6
Published
REST API for redux infrastructure.
Downloads
18
Readme
Introduction
redux-restapi
is an utility for integrating a REST api with Redux. It helps you, to easily integrate your calls to a REST api with your store. It generates actions
and reducer
for making the calls to the server and can easly be combined with your actions.
All calls are made using superagent.
Installation
node:
npm install redux-restapi --save
Works with browserify and should work with webpack
Example
Let's say we have this:
- GET: http://mywebsite.com/api/v1/companies (will list all the companies)
- DELETE: http://mywebsite.com/api/v1/companies/:id (will delete company with id)
- POST: http://mywebsite.com/api/v1/companies (will create a company)
Main file
index.js
import rest from "redux-restapi";
rest.setBaseUrl("http://mywebsite.com/api/v1/");
rest.setHeaders({
"Content-Type": "application/json",
"x-api-key": "apiKey123"
});
Reducer
reducers/companies.js
import rest from "redux-restapi";
import reduceReducers from "reduce-reducers";
// Default reducer, this will be combined
// with the REST reducer
let defaultReducer = (state = {}, action = {}) => {
switch (action.type) {
case "myType": // do extra stuff
return {
...state,
"extra": true
};
default:
return state;
}
};
// Create REST reducer
let restReducer = rest.createReducer(rest.createEndpoint("companies"));
// Combine our reducer with rest reducer
export default reduceReducers(restReducer, defaultReducer);
This will create a reducer that can handle (pending, list, create, remove, update) action and handle extra action you want to handle.
Actions
actions/companies.js
import rest from "redux-restapi";
let endpoint = rest.createEndpoint("companies");
let restActions = rest.createActions(endpoint);
export default {
select: (item) => {
return {
type: "positions/select",
payload: item
}
},
...restActions
};
store.js
import companiesReducer from "reducers/companies";
let rootReducer = combineReducers({
routing: routerReducer,
companies: companiesReducer
});
let initialState = {};
let store = createStore(rootReducer, initialState, applyMiddleware(thunkMiddleware));
In your containers you can use this actions:
ExemplaContainer.js
import actions from "actions/companies";
const mapState = (state) => {
return {
...
};
};
const mapDispatch = function (dispatch) {
let { create, remove, list } = actions;
return {
onAdd: (company) => {
dispatch(create(company));
},
onDelete: (item) => {
dispatch(remove(item._id));
},
onLoad: () => {
dispatch(actions.list());
}
};
};
export default connect(mapState, mapDispatch)(Example);
Tests
gulp test