Last active
February 11, 2019 19:02
-
-
Save aigoncharov/ddde680cffc099e5b6b967f683c3bd13 to your computer and use it in GitHub Desktop.
Reducer organization - taking a step further
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
const actionTypeJediCreateInit = 'jedi-app/jedi-create-init' | |
const actionTypeJediCreateSuccess = 'jedi-app/jedi-create-success' | |
const actionTypeJediCreateError = 'jedi-app/jedi-create-error' | |
const reducerJediInitialState = { | |
loading: false, | |
data: [], | |
error: undefined, | |
} | |
const reducerJediMap = { | |
[actionTypeJediCreateInit]: (state) => ({ | |
...state, | |
loading: true, | |
}), | |
[actionTypeJediCreateSuccess]: (state, action) => ({ | |
loading: false, | |
data: [...state.data, action.payload], | |
error: undefined, | |
}), | |
[actionTypeJediCreateError]: (state, action) => ({ | |
...state, | |
loading: false, | |
error: action.payload, | |
}), | |
} | |
const reducerJedi = (state = reducerJediInitialState, action) => { | |
// Pick a reducer by action type | |
const reducer = reducerJediMap[action.type] | |
if (!reducer) { | |
// Return state unchanged if we did not find a suitable reducer | |
return state | |
} | |
// Run suitable reducer if found one | |
return reducer(state, action) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment