Skip to content

Instantly share code, notes, and snippets.

@PCreations
Last active May 25, 2018 18:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PCreations/1e322513455a55700ffef30282757bb7 to your computer and use it in GitHub Desktop.
Save PCreations/1e322513455a55700ffef30282757bb7 to your computer and use it in GitHub Desktop.
const createPaginator = (endpoint, resultKey) {
const requestPage = (page) => ({
type: 'REQUEST_PAGE',
payload: {
page
},
meta: {
endpoint,
resultKey
}
})
const receivePage = (page, results) => ({
type: 'RECEIVE_PAGE',
payload: {
page,
results
}
})
const pages = pages = {}, action = {}) => {
switch (action.type) {
case 'REQUEST_PAGE':
return {
...pages,
[action.payload.page]: {
ids: [],
fetching: true
}
}
case 'RECEIVE_PAGE':
return {
...pages,
[action.payload.page]: {
ids: action.payload.results.filter(item => item.id),
fetching: false
}
}
default:
return pages
}
}
const currentPage = (currentPage = 1, action = {}) =>
action.type == ‘REQUEST_PAGE’ ? action.payload.page : currentPage
const onlyForEndpoint = (reducer) => (state = {}, action = {}) =>
typeof action.meta == ‘undefined’ ? state : action.meta.endpoint == endpoint ? reducer(state, action) : state
const itemsReducer = (items = {}, action = {}) {
switch (action.type) {
case 'RECEIVE_PAGE':
let _items = {}
for (let item of action.payload.results) {
_items = {
..._items,
[item.id]: item
}
}
return {
...items,
..._items
}
default:
return items
}
}
const reducer = onlyForEndpoint(
combineReducers({
pages,
currentPage
})
)
return {
requestPage,
receivePage,
reducer,
itemsReducer: onlyForEndpoint(itemsReducer)
}
}
@kairat-kempirbaev
Copy link

22 const pages = pages = {}, action = {}) => {

const pages = (pages = {}, action = {}) => {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment