Skip to content

Instantly share code, notes, and snippets.

@dewey92
Last active April 22, 2018 10:25
Show Gist options
  • Select an option

  • Save dewey92/d2565772a6439dbd46a3b6bad8c80615 to your computer and use it in GitHub Desktop.

Select an option

Save dewey92/d2565772a6439dbd46a3b6bad8c80615 to your computer and use it in GitHub Desktop.
HOR
// 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