Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import union from 'lodash/union'
- import { handleActions } from 'redux-actions'
- import { initialState } from 'mocks/state/initialState'
- import { set } from 'dot-prop-immutable'
- // creates a reducer managing pagination
- const paginationReducer = ({ types }) => {
- if (!Array.isArray(types) || types.length !== 4) {
- throw new Error('Expected types to be an array of four elements.')
- }
- if (!types.every(t => typeof t === 'string')) {
- throw new Error('Expected types to be strings.')
- }
- const [requestType, successType, failureType, clearSearchType] = types
- const updatePagination = handleActions({
- [`${requestType}`]: (state, action) => {
- state = set(state, 'fetching', true)
- return state
- },
- [`${successType}`]: (state, action) => {
- const { result } = action.payload.response
- const ids = union(state.ids, Array.isArray(result) ? result : [result])
- state = set(state, 'fetching', false)
- state = set(state, 'ids', ids)
- return state
- },
- [`${failureType}`]: (state, action) => {
- state = set(state, 'fetching', false)
- return state
- }
- }, {
- fetching: false,
- ids: []
- })
- return handleActions({
- [`${requestType}`]: (state, action) => {
- const { limit, skip, term } = action.meta.params
- if (term) {
- state = set(state, 'search', { term })
- state = set(state, 'search', updatePagination(state.search, action))
- } else {
- state = set(state, 'limit', limit)
- state = set(state, 'skip', skip)
- state = set(state, `pages.${(skip / limit) + 1}`, updatePagination(state.pages[(skip / limit) + 1], action))
- }
- return state
- },
- [`${successType}`]: (state, action) => {
- const { limit, skip, search } = state
- state = search.fetching
- ? set(state, 'search', updatePagination(state.search, action))
- : set(state, `pages.${(skip / limit) + 1}`, updatePagination(state.pages[(skip / limit) + 1], action))
- return state
- },
- [`${failureType}`]: (state, action) => {
- const { limit, skip, search } = state
- state = search.fetching
- ? set(state, 'search', updatePagination(state.search, action))
- : set(state, `pages.${(skip / limit) + 1}`, updatePagination(state.pages[(skip / limit) + 1], action))
- return state
- },
- [`${clearSearchType}`]: (state, action) => {
- state = set(state, 'search', { fetching: false, ids: [] })
- return state
- }
- }, initialState)
- }
- export default paginationReducer
Add Comment
Please, Sign In to add comment