Last active
April 22, 2018 10:25
-
-
Save dewey92/d2565772a6439dbd46a3b6bad8c80615 to your computer and use it in GitHub Desktop.
HOR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // reducerHelper.js | |
| export const createAsyncReducer = (initialState, asyncAction) => | |
| (state = initialState, action) => { | |
| switch (action.type) { | |
| case asyncAction.request.type: | |
| return { | |
| ...state, | |
| asyncState: AsyncState.loading | |
| } | |
| case asyncAction.success.type: | |
| return { | |
| ...state, | |
| data: action.payload.result, | |
| asyncState: AsyncState.loaded | |
| } | |
| case asyncAction.failed.type: | |
| return { | |
| ...state, | |
| asyncState: AsyncState.error, | |
| error: action.payload.error | |
| } | |
| default: | |
| return state | |
| } | |
| } | |
| // ************************************************* // | |
| // reducer.js | |
| import { combineReducers } from 'redux' | |
| import { createAsyncReducer } from './reducerHelper' // <- INI | |
| const AsyncState = { | |
| idle: 'idle', | |
| loading: 'loading', | |
| loaded: 'loaded', | |
| error: 'error' | |
| } | |
| const initialState = { | |
| user: { | |
| data: {}, | |
| asyncState: AsyncState.idle, | |
| }, | |
| post: { | |
| data: {}, | |
| asyncState: AsyncState.idle, | |
| }, | |
| } | |
| export default combineReducers({ // <- Use combineReducers | |
| user: createAsyncReducer(initialState.user, getUser), // <- Less code | |
| post: createAsyncReducer(initialState.post, getPost), // <- Less code | |
| ... | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment