Skip to content

Instantly share code, notes, and snippets.

@tejasbubane
Last active February 24, 2021 21:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tejasbubane/aa7477ca98c4c667a49d3eaf692dc717 to your computer and use it in GitHub Desktop.
Save tejasbubane/aa7477ca98c4c667a49d3eaf692dc717 to your computer and use it in GitHub Desktop.
Curried Reducers
import { combineReducers } from "redux";
import listReducer from "./listReducer";
const rootReducer = combineReducers({
products: listReducer("products"),
orders: listReducer("orders"),
warehouse_locations: listReducer("warehouse_locations")
});
export default rootReducer; // later configured in store
// Paginated List Reducer
import { combineReducers } from "redux";
const listReducer = listType => {
const type = listType.toUpperCase();
const status = (state = null, action) => {
switch (action.type) {
case `REQUEST_${type}`:
return "inprogress";
case `FETCH_${type}_SUCCESS`:
return "success";
case `FETCH_${type}_FAILURE`:
return "failure";
default:
return state;
}
};
const items = (state = [], action) => {
switch (action.type) {
case `FETCH_${type}_SUCCESS`:
return action.items;
case `FETCH_${type}_FAILURE`:
return []; // reset existing data
default:
return state;
}
};
// Total number of items in the list (in all pages)
const totalCount = (state = 0, action) => {
switch (action.type) {
case `FETCH_${type}_SUCCESS`:
return action.totalCount;
case `FETCH_${type}_FAILURE`:
return 0; // reset existing data
default:
return state;
}
};
const totalPages = (state = 0, action) => {
switch (action.type) {
case `FETCH_${type}_SUCCESS`:
return action.totalPages;
case `FETCH_${type}_FAILURE`:
return 0; // reset existing data
default:
return state;
}
};
return combineReducers({
status,
items,
totalCount,
totalPages
});
};
export default listReducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment