Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Factory used to create reducer and actions to perfom fetch functions.
- * @module fetch.factory
- * @member redux/factories
- */
- export const fetchActionConstants = (reducerId) => ({
- FETCH_REQUEST: `${reducerId}::FETCH_REQUEST`,
- FETCH_SUCCESS: `${reducerId}::FETCH_SUCCESS`,
- FETCH_FAILURE: `${reducerId}::FETCH_FAILURE`,
- FETCH_RESET: `${reducerId}::FETCH_RESET`,
- })
- const DEFAULT_STATE = {
- isFetching: false,
- error: undefined,
- lastUpdated: undefined,
- data: undefined,
- }
- // ======================================
- // Reducer factory
- // ======================================
- const defaultDataFormatter = payload => payload.data
- /**
- * @param {string} reducerId - a unique name to identify the reducer
- * @param {Object} options - Reducer configuration.
- {
- iniData?: undefined, // initial value for data field of state
- dataFormatter?: payload => payload.data, // Function called after succes fetch GET to assign
- // a new value
- }
- * to data field of state.
- * @returns {Function} reducer for fetch with GET method
- */
- export default (
- reducerId,
- {
- iniData = undefined,
- dataFormatter = defaultDataFormatter,
- } = {}
- ) => {
- // Action constants
- const {
- FETCH_REQUEST, FETCH_SUCCESS, FETCH_FAILURE, FETCH_RESET,
- } = fetchActionConstants(reducerId)
- // Initial state
- const initialState = {
- ...DEFAULT_STATE,
- data: iniData,
- }
- // Return the fetch reducer
- return (state = initialState, action) => {
- const { type, payload } = action
- switch (type) {
- case FETCH_REQUEST:
- return {
- ...state,
- isFetching: true,
- error: undefined,
- }
- case FETCH_SUCCESS:
- return {
- ...state,
- isFetching: false,
- error: undefined,
- lastUpdated: payload.receivedAt,
- data: dataFormatter(payload),
- }
- case FETCH_FAILURE:
- return {
- ...state,
- isFetching: false,
- error: payload,
- }
- case FETCH_RESET:
- return initialState
- default:
- return state
- }
- }
- }
- // ======================================
- // Action creators
- // ======================================
- export const fetchRequest = (type) => ({ type })
- export const fetchSuccess = (type, response: { data, headers?}) => ({
- type,
- payload: {
- data: response.data,
- headers: response.headers,
- receivedAt: new Date(),
- },
- })
- export const fetchFailure = (type, error) => ({
- type,
- payload: error,
- error: true,
- })
- export const resetFetch = (type) => ({ type })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement